通过键合并 2 个字典而不覆盖
Merging 2 dictionaries by keys without overwriting
假设我有 2 部词典:
ss = {'1':{'tier 1': {'valid_detailed': 66, 'valid_approx': 68, 'valid_unmapped': 56, 'valid_total': 288}}}
tt = {'1':{'tier 2': {'valid_detailed': 44, 'valid_approx': 33, 'valid_unmapped': 22, 'valid_total': 111}}}
我想将它们合并在一起,但不覆盖键,只有当键不同时才添加新项目。基本上,我想得到这个:
zz = {'1':{'tier 1': {'valid_detailed': 66, 'valid_approx': 68, 'valid_unmapped': 56, 'valid_total': 288}, 'tier 2': {'valid_detailed': 44, 'valid_approx': 33, 'valid_unmapped': 22, 'valid_total': 111}}}
到目前为止,我试过这个:
result_dict = {}
dicts = [ss, tt]
for d in dicts:
for k, v in d.items():
result_dict.setdefault(k, []).extend(v)
差不多可以了。我最终得到了这个,这不是我想要的:
result_dict
>>>{'tier 1': ['valid_all_row', 'all_all_row', 'valid_all_row', 'all_all_row'],'tier 2': ['valid_all_row', 'all_all_row', 'valid_all_row', 'all_all_row']}
我怎样才能做到这一点?
ss = {'tier 1': {'valid_detailed': 66, 'valid_approx': 68, 'valid_unmapped': 56, 'valid_total': 288}}
tt = {'tier 2': {'valid_detailed': 44, 'valid_approx': 33, 'valid_unmapped': 22, 'valid_total': 111}}
zz={}
for i in ss.keys():
zz[i]=ss[i]
for i in tt.keys():
zz[i]=tt[i]
结果:
zz={'tier 1': {'valid_detailed': 66,
'valid_approx': 68,
'valid_unmapped': 56,
'valid_total': 288},
'tier 2': {'valid_detailed': 44,
'valid_approx': 33,
'valid_unmapped': 22,
'valid_total': 111}}
假设我有 2 部词典:
ss = {'1':{'tier 1': {'valid_detailed': 66, 'valid_approx': 68, 'valid_unmapped': 56, 'valid_total': 288}}}
tt = {'1':{'tier 2': {'valid_detailed': 44, 'valid_approx': 33, 'valid_unmapped': 22, 'valid_total': 111}}}
我想将它们合并在一起,但不覆盖键,只有当键不同时才添加新项目。基本上,我想得到这个:
zz = {'1':{'tier 1': {'valid_detailed': 66, 'valid_approx': 68, 'valid_unmapped': 56, 'valid_total': 288}, 'tier 2': {'valid_detailed': 44, 'valid_approx': 33, 'valid_unmapped': 22, 'valid_total': 111}}}
到目前为止,我试过这个:
result_dict = {}
dicts = [ss, tt]
for d in dicts:
for k, v in d.items():
result_dict.setdefault(k, []).extend(v)
差不多可以了。我最终得到了这个,这不是我想要的:
result_dict
>>>{'tier 1': ['valid_all_row', 'all_all_row', 'valid_all_row', 'all_all_row'],'tier 2': ['valid_all_row', 'all_all_row', 'valid_all_row', 'all_all_row']}
我怎样才能做到这一点?
ss = {'tier 1': {'valid_detailed': 66, 'valid_approx': 68, 'valid_unmapped': 56, 'valid_total': 288}}
tt = {'tier 2': {'valid_detailed': 44, 'valid_approx': 33, 'valid_unmapped': 22, 'valid_total': 111}}
zz={}
for i in ss.keys():
zz[i]=ss[i]
for i in tt.keys():
zz[i]=tt[i]
结果:
zz={'tier 1': {'valid_detailed': 66,
'valid_approx': 68,
'valid_unmapped': 56,
'valid_total': 288},
'tier 2': {'valid_detailed': 44,
'valid_approx': 33,
'valid_unmapped': 22,
'valid_total': 111}}