This one does the job.
def filterDict(complex_dict):
filtered_dict = {}
for a in complex_dict.values():
for b in a:
for c in b.values():
for d in c:
for e, f in d.items():
if e not in filtered_dict:
filtered_dict[e] = {}
filtered_dict[e].update(f)
return filtered_dict
complex_dict = {'lst_0': [{'127.0.0.1': [{'key2': {'CHG': ['entry8'],
'asm': 'entry7'}}]},
{'127.0.0.1': [{'key2': {'DU': 'entry10',
'PL': 'entry9'}}]},
{'127.0.0.1': [{'key2': {'DU': 'entry12',
'SL': 'entry11'}}]}],
'lst_1': [{'127.0.0.1': [{'key1': {'CHG': ['entry2'],
'asm': 'entry1'}}]},
{'127.0.0.1': [{'key1': {'DU': 'entry4',
'PL': 'entry3'}}]},
{'127.0.0.1': [{'key1': {'DU': 'entry6',
'SL': 'entry5'}}]}]}
print(filteredDict(complex_dict))
## OUTPUT:
# {'key1': {'CHG': ['entry2'],
# 'DU': 'entry6',
# 'PL': 'entry3',
# 'SL': 'entry5',
# 'asm': 'entry1'},
# 'key2': {'CHG': ['entry8'],
# 'DU': 'entry12',
# 'PL': 'entry9',
# 'SL': 'entry11',
# 'asm': 'entry7'}}
I guess there's nothing to explain here since this is just a bunch of nested loops to get the values needed for the filtered dictionary.
I'm quite curious why you have this kind of structure for your dictionary. If you can and able to, I suggest restructuring your dictionary, so you won't have to deal with this kind of nested loops.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…