我有一个嵌套字典,如下所示。我需要从字典中弹出一个键及其值,并在嵌套字典中将该键的整个路径放入列表中。
a={'aa': {'1': {'bb':{'2': {'cc' : ['xx', 'yy']},
'3': {'dd' : ['zz', 'yy']}}},
'11': {'bbb':{'22': {'cc': ['xxx', 'yyy']},
'33': {'dd' : ['zz', 'yy']}}}}}
我正在寻找一个像这样的
lis = [{'aa': {'1': {'bb':{'3': {'dd' : ['zz', 'yy']}, {'aa': {'11': {'bbb':{'33': {'dd' : ['zz', 'yy']}]
我的代码如下。它会弹出ditionary中的值,但不能将其存储在列表中。有没有办法可以将弹出的值与其整个路径存储在上面的列表中?
def delete_keys_from_dict(dict_del, lst_keys):
for k in lst_keys:
try:
dict_del.pop(k)
except KeyError:
pass
for v in dict_del.values():
if isinstance(v, dict):
delete_keys_from_dict(v, lst_keys)
return dict_del
delete_keys_from_dict(a, ['dd'])
答案 0 :(得分:0)
我认为您正在寻找poped值。您可以在从字典中删除时将poped值添加到列表中。
a={'aa': {'1': {'bb':{'2': {'cc' : ['xx', 'yy']},
'3': {'dd' : ['zz', 'yy']}}},
'11': {'bbb':{'22': {'cc': ['xxx', 'yyy']},
'33': {'dd' : ['zz', 'yy']}}}}}
def delete_keys_from_dict(dict_del, lst_keys,res=[]):
for k in lst_keys:
try:
res.append((k,dict_del.pop(k)))
except KeyError:
pass
for v in dict_del.values():
if isinstance(v, dict):
delete_keys_from_dict(v, lst_keys)
return dict_del,res
result = delete_keys_from_dict(a, ['dd'])
print('Updated Dictionary : ' + str(result[0]))
print('Deleted : ' + str(result[1]))
OutputL
Updated Dictionary : {'aa': {'1': {'bb': {'3': {}, '2': {'cc': ['xx', 'yy']}}}, '11': {'bbb': {'22': {'cc': ['xxx', 'yyy']}, '33': {}}}}}
Deleted : [('dd', ['zz', 'yy']), ('dd', ['zz', 'yy'])]