我想提取所有串列并從具有多個級別的嵌套字典中修改它們,并且串列可以是任何級別中的值。
例如:
test = {
'Type 1': {
'Type1_mainkey1': {
'Type1_key2': {
'Type1_key2_key1': [
'Type1_list1'
],
'Type1_key2_key2': [
'Type1_list2'
],
'Type1_key2_key2': [
'Type1_list3',
'Type1_list4'
]
}
}
},
'Type 2': {
'Type2_mainkey1': {
'Type2_key2': [
'Type2_list1',
'Type2_list2'
]},
'Type2_key3': {
'Type2_key3_key1': [
'Type2_list3',
'Type2_list4'
]
}
}
}
這是可能存在的字典型別。我想知道是否有一種方法可以提取串列并更新字典。
到目前為止我的功能:
def find_list(data):
if not any([isinstance(data.get(k), dict) for k in data]):
return data
else:
for dkey in data:
if isinstance(data.get(dkey), dict):
return find_list(data.get(dkey))
else:
continue
在運行這個:
out = find_list(test)
我的輸出是:
{'Type1_key2_key1': ['Type1_list1'],
'Type1_key2_key2': ['Type1_list3', 'Type1_list4']}
而預期的輸出是所有串列項及其鍵(以便我可以修改串列和更新)
uj5u.com熱心網友回復:
在下面的示例中,我唯一不同的是在每個遞回步驟中收集結果并添加到以前的回傳中。我添加了一些行內評論,希望能更好地解釋。
def find_list(data):
d = {} # initialize collection object to hold results
if not any([isinstance(data.get(k), dict) for k in data]):
return data
else:
for dkey in data:
if isinstance(data.get(dkey), dict):
# add results of each recursive call to the collection
d.update(find_list(data.get(dkey)))
return d # return the collection of results
在此示例中使用您的test字典會給出以下輸出:
{
'Type1_key2_key1': ['Type1_list1'],
'Type1_key2_key2': ['Type1_list3', 'Type1_list4'],
'Type2_key2': ['Type2_list1', 'Type2_list2'],
'Type2_key3_key1': ['Type2_list3', 'Type2_list4']
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453473.html
