将作为值存储在嵌套字典中的Python列表聚合到一个任意级别的列表中 [英] Aggregate Python lists stored as values in a nested dictionary into one list for arbitrary levels
问题描述
假设我有一个嵌套的字典,在某种程度上,终端值是列表.例如:
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]}}
我想将列表值聚合到[1,2,3,4,5,6,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)
如何使其更紧凑,并能够处理任意级别?也就是说,我知道所有列表都处于同一级别,但是我不知道它的深度,所以在我提供的代码中,我实际上需要不确定数量的for循环.
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.
推荐答案
您可以使用递归:
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]
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
这篇关于将作为值存储在嵌套字典中的Python列表聚合到一个任意级别的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!