I have the below dictionary and want to put all the fruit into a new dictionary ie the output would be
{"Apples":1, "Banana":1, "Pear":1, "Orange":2}.
I keep stumbling at the point where Andy has a dictionary in a dictionary which I cannot figure out how to deal with.
{
"Martin":{"Apples":1},
"Andy":{"Dad":{"Banana":1}},
"Lucy":{"Pear":1,"Orange":2}
}
Any advice please.
CodePudding user response:
You can use python's built in isinstance to check what is the type of your value, and recursive calls to process the value as the flat data:
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)
Which gives the following:
{'Apples': 1, 'Banana': 1, 'Pear': 1, 'Orange': 2}