我有下面的字典,我想把所有的水果放入一个新的字典中,即输出将是
{"Apples":1, "Banana":1, "Pear":1, "Orange":2}.
我总是被安迪的字典里有字典这一点绊倒,我不知道该怎么处理。
{
"Martin":{"Apples":1},
"Andy":{"Dad":{"Banana":1}},
"Lucy":{"Pear":1,"Orange":2}
}
有什么建议吗
你可以使用python内置的isinstance来检查你的值的类型,并递归调用来处理这个值作为平面数据:
data = {
"Martin":{"Apples":1},
"Andy":{"Dad":{"Banana":1}},
"Lucy":{"Pear":1,"Orange":2}
}
fruits = {}
def add_fruits(data):
for key, value in data.items():
if isinstance(value, dict):
# it's a dict go one more level
add_fruits(value)
else: # it's a fruit
fruits[key] += value
add_fruits(data)
print(fruits)
给出如下:
{'Apples': 1, 'Banana': 1, 'Pear': 1, 'Orange': 2}