[英]Python: Building list of lists using dictionary recursion
我有一个非常复杂的问题,我有点希望在这里解决问题:
我有一本字典:
{
"1": {
"1.1": {
"1.1.1": {}
},
"1.2": {
"1.2.1": {}
}
},
"2": {
"2.1": {
"2.1.1": {}
},
"2.2": {
"2.2.2": {}
}
}
}
其结构不会总是相同(即,在任何子字典中可能有进一步的嵌套或更多键)。 我需要能够根据一些输入生成一个明确排序的列表列表(包含的子列表不需要排序)。 列表的结构基于字典。 考虑到字典中的所有键,列表列表如下所示:
[['1', '2'], ['1.2', '1.1'], ['1.1.1'], ['1.2.1'], ['2.2', '2.1'], ['2.1.1'], ['2.2.2']]
也就是说,第一个子列表包含字典最高级别的两个键。 第二个子列表包含第一个“最高级别”键下的两个键。 第三个和第四个子列表包含字典“第二级”下可用的键。 (等等)
我需要一个 function ,它会根据输入(即嵌套字典中的任何键)返回正确的列表列表。 举些例子):
function('2.2.2')
>>> [['2'], None, None, None, ['2.2'], None, ['2.2.2']] # or [['2'], [], [], [], ['2.2'], [], ['2.2.2']]
function('1.1')
>>> [['1'], ['1.1'], None, None, None, None, None] # or [['1'], ['1.1'], [], [], [], [], []]
function('1.2.1')
>>> [['1'], ['1.2'], None, ['1.2.1'], None, None, None] # or [['1'], ['1.2'], [], ['1.2.1'], None, [], []]
这几乎就像我需要能够在递归时“知道”字典的结构。 我一直在想,如果我可以在字典中找到输入键然后跟踪它,我将能够生成列表列表,但是
您的主列表只是 dict 结构中所有键的深度优先列表。 得到这个相当容易:
def dive_into(d):
if d and isinstance(d, dict):
yield list(d.keys())
for v in d.values():
yield from dive_into(v)
d = {
"1": {
"1.1": {
"1.1.1": {}
},
"1.2": {
"1.2.1": {}
}
},
"2": {
"2.1": {
"2.1.1": {}
},
"2.2": {
"2.2.2": {}
}
}
}
master_list = list(dive_into(d))
# [['1', '2'], ['1.1', '1.2'], ['1.1.1'], ['1.2.1'], ['2.1', '2.2'], ['2.1.1'], ['2.2.2']]
接下来,您的function
需要找到给定键的所有父键,并且只返回给定键的路径中的键。 由于您的键始终具有格式<parent>.<child>.<grandchild>
,因此您只需要遍历此列表,并返回key.startswith(e)
为True
的任何元素e
:
def function(key):
lst = [[e for e in keys if key.startswith(e)] for keys in master_list]
return [item or None for item in lst]
用你的例子测试这个:
>>> function('2.2.2')
Out: [['2'], None, None, None, ['2.2'], None, ['2.2.2']]
>>> function('1.1')
Out: [['1'], ['1.1'], None, None, None, None, None]
>>> function('1.2.1')
Out: [['1'], ['1.2'], None, ['1.2.1'], None, None, None]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.