If there are n number of nested dictionaries of varying values and length of keys in a list:
original_list =
[
{'animal': {'mammal': {'herbivore': 'zebra'}}},
{'animal': {'mammal': {'herbivore': 'deer'}}},
{'animal': {'mammal': {'carnivore': 'tiger'}}},
{'animal': {'mammal': {'herbivore': 'lion'}}},
{'furniture': {'chair'}}
]
How to aggregate values with the same nested keys to obtain a result such as:
[
{'animal': {'mammal': {'herbivore': 'zebra', 'deer'}}},
{'animal': {'mammal': {'carnivore': 'tiger', 'lion'}}},
{'furniture': 'chair'}
]
or a more condensed view such as:
[
{'animal':
{'mammal':
{'herbivore': ['zebra', 'deer']},
{'carnivore': ['tiger', 'lion']}
}
},
{'furniture': ['chair']}
]
or
[
{'animal': {'mammal': {'herbivore': ['zebra', 'deer']}}},
{'animal': {'mammal': {'carnivore': ['tiger', 'lion']}}},
{'furniture': ['chair']}
]
I have tried this:
from collections import defaultdict
d = defaultdict(list)
for item in original_list:
for k, v in item.items():
d[k].append(v)
But that just aggregates at the root of the list (and not at inner levels) like:
[
{
'animal':
[
{'mammal': {'herbivore': 'zebra'}}},
{'mammal': {'herbivore': 'deer'}}},
{'mammal': {'carnivore': 'tiger'}}},
{'mammal': {'herbivore': 'lion'}}}
],
}
{
'furniture': {'chair'}
}
]