字典中的字典,如何删除和聚合所有数据
Dictionary in a Dictionary, how to remove and aggregate all the data
我有下面的字典,想把所有的水果放到一个新的字典中,即输出是
{"Apples":1, "Banana":1, "Pear":1, "Orange":2}.
我一直纠结于 Andy 的字典里有一本我不知道如何处理的字典。
{
"Martin":{"Apples":1},
"Andy":{"Dad":{"Banana":1}},
"Lucy":{"Pear":1,"Orange":2}
}
有什么建议吗
您可以使用 python 的内置 isinstance to check what is the type of your value, and recursive calls 将值处理为平面数据:
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}
我有下面的字典,想把所有的水果放到一个新的字典中,即输出是
{"Apples":1, "Banana":1, "Pear":1, "Orange":2}.
我一直纠结于 Andy 的字典里有一本我不知道如何处理的字典。
{
"Martin":{"Apples":1},
"Andy":{"Dad":{"Banana":1}},
"Lucy":{"Pear":1,"Orange":2}
}
有什么建议吗
您可以使用 python 的内置 isinstance to check what is the type of your value, and recursive calls 将值处理为平面数据:
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}