[英]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.