Suppose I have a nested dictionary where, at some level, the terminal values are lists. For example:
nested_dict = {1 : {'a' : [1,2,3], 'b' : [4,5]},
2 : {'a' : [6], 'b' : [7,8,9]}}
I want to aggregate the list values into [1,2,3,4,5,6,7,8,9]
. For two levels I have
values = []
for key1 in nested_dict.keys():
for key2 in nested_dict[key1].keys():
for value in nested_dict[key1][key2]:
values.append(value)
How can this be made more compact, and such that it handles arbitrary levels? That is, I know all the lists to be at the same level, but I don't know how deep, so in the code I provide I would effectively need an indeterminate number of for loops.
Not a duplicate of how to extract multi level dictionary keys/values in python because they only show up to two levels.
You can use recursion:
nested_dict = {1 : {'a' :[1,2,3], 'b': [4,5]}, 2 : {'a' : [6], 'b' : [7,8,9]}}
def get_lists(d):
r = [b if isinstance(b, list) else get_lists(b) for b in d.values()]
return [i for b in r for i in b]
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
来源:https://stackoverflow.com/questions/51426716/aggregate-python-lists-stored-as-values-in-a-nested-dictionary-into-one-list-for