[英]How to create a dictionary while iterating through a nested dictionary in python?
我有一个默认字典,它是一个嵌套字典。 我想遍历字典以创建两个单独的字典 left_dict 和 right_dict。 有人可以帮忙吗?
left_dict = {}
right_dict = {}
d1 = {'A': {'left': {'10.xxx.77.1': [5]}, 'right': {'10.xxx.77.2': [6]}}, 'B': {'left': {'10.xxx.77.1': [7]}, 'right': {'10.xxx.77.2': [8]}}}
d = defaultdict(list)
for k , v in d1.items():
if isinstance(v, dict):
for j, l in v.items():
if isinstance(l, dict):
for m, n in l.items():
d[m].append(n)
print(d)
实际输出是
{'10.xxx.77.1': [[5], [7]], '10.xxx.77.2': [[6], [8]]}
预期输出是
left_dict = {'10.xxx.77.1': [5, 7]}
right_dict = {'10.xxx.77.2': [6, 8]}
我想这就是你的目标。
#left_dict = {}
#right_dict = {}
d1 = {'A': {'left': {'10.xxx.77.1': [5]}, 'right': {'10.xxx.77.2': [6]}}, 'B': {'left': {'10.xxx.77.1': [7]}, 'right': {'10.xxx.77.2': [8]}}}
d = {}
for k, dict1 in d1.items():
if not isinstance(dict1, dict):
continue
for pos, dict2 in dict1.items():
if not isinstance(dict2, dict):
continue
if not isinstance(d.get(pos, None), dict):
d[pos]={}
for port, v_list in dict2.items():
d[pos][port]=d[pos].get(port, [])+v_list
print(d)
# {'left': {'10.xxx.77.1': [5, 7]}, 'right': {'10.xxx.77.2': [6, 8]}}
我认为下面的代码将满足您的目的:
d1 = {
'A': {'left': {'10.xxx.77.1': [5]}, 'right': {'10.xxx.77.2': [6]}},
'B': {'left': {'10.xxx.77.1': [7]}, 'right': {'10.xxx.77.2': [8]}},
'C': {'left': {'10.xxx.77.1': [9, 11]}, 'right': {'10.xxx.77.2': [10, 12]}}
}
d = {}
left_dict = {}
right_dict = {}
for k , v in d1.items():
for j, l in v.items():
if not isinstance(d.get(j), dict):
d[j] = {}
for m, n in l.items():
d[j][m] = d[j].get(m, []) + n
left_dict = d.get('left')
right_dict = d.get('right')
print(d)
print(f'left_dict = {left_dict}\nright_dict = {right_dict}')
你可以做这样的事情。
# Stores values to left and right dicts
def fill_dict(src_d, des_d):
for k, v in src_d.items():
if k not in des_d:
des_d[k] = v
else:
des_d[k].extend(v)
left_dict = {}
right_dict = {}
d1 = {'A': {'left': {'10.xxx.77.1': [5]}, 'right': {'10.xxx.77.2': [6]}}, 'B': {'left': {'10.xxx.77.1': [7]}, 'right': {'10.xxx.77.2': [8]}}}
for k , v in d1.items():
for ks, vs in v.items():
if ks == 'left':
fill_dict(vs, left_dict)
elif ks == 'right':
fill_dict(vs, right_dict)
print(left_dict)
print(right_dict)
Output
{'10.xxx.77.1': [5, 7]}
{'10.xxx.77.2': [6, 8]}
使用递归函数解决并为灵活性而设计(即对于所要求的内容过于复杂,但我喜欢这种做法)。
# added additional depth to demo input dictionary
dictionary_li = [{'A': {'C': {'left': {'10.xxx.77.1': [5]}, 'right': {'10.xxx.77.2': [6]}}}, 'B': {'left': {'10.xxx.77.1': [7]}, 'right': {'10.xxx.77.2': [8]}}}]
def recursive_key_search(dictionary_li, key, key_di):
'''extract values belonging to key'''
flatten_li = []
for di in dictionary_li:
for k in di:
if key not in di and di[k]:
flatten_li.append(di[k])
else:
if key not in key_di:
key_di[key] = []
elif di[key] not in key_di[key]: # key can occur at different depths
key_di[key].append(di[key]) # no assumptions on format made at this time
# check if additional iteration necessary
if sum([1 for di in flatten_li for k in di if type(di[k]) == dict]) > 0:
recursive_key_search(flatten_li, key, key_di)
return(key_di)
def merge_dictionaries(flatten_li, merge=False):
'''merge values within dictionary'''
out_di = {}
for di in flatten_li:
for k in di:
# will attempt to combine values
if merge:
if k not in out_di:
out_di[k] = di[k]
elif type(di[k]) == type(out_di[k]):
out_di[k] += di[k]
else:
out_di[k].append(di[k])
# will keep values separated
else:
if k not in out_di:
out_di[k] = []
out_di[k].append(di[k])
return(out_di)
for key in ["left", "right"]:
key_search = recursive_key_search(dictionary_li, key, {})[key]
#print(key_search)
merge = merge_dictionaries(key_search, True)
print(key+":", merge)
输出
left: {'10.xxx.77.1': [7, 5]}
right: {'10.xxx.77.2': [8, 6]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.