Aggregate Python lists stored as values in a nested dictionary into one list for arbitrary levels [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-08 07:16:44

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!