从dictionary中的值中删除嵌套键的Python代码

ryhaxcpt  于 2023-03-24  发布在  Python
关注(0)|答案(2)|浏览(129)

目前,我有一个嵌套字典,键为“Apple”和“Mango”。在值中,我们再次将“0”作为键。

Fruits = {
  "Apple": {
    "0": 0.066
  },
  "Mango": {
    "0": 0.933
  }
}

相反,我希望它看起来像:

Fruits = {
  "Apple": 0.066
  ,
  "Mango": 0.933
}
5jdjgkvh

5jdjgkvh1#

试试看:

Fruits = {k: v['0'] for k, v in Fruits.items()}
dw1jzc5e

dw1jzc5e2#

Fruits = {
  "Apple": {
    "0": 0.066
  },
  "Mango": {
    "0": 0.933
  }
}

new_fruits = {}

for fruit, values in Fruits.items():
    new_fruits[fruit] = values["0"]

print(new_fruits)

输出:

{'Apple': 0.066, 'Mango': 0.933}

相关问题