通过键合并2个字典而不会覆盖

时间:2019-11-14 19:39:38

标签: python-3.x dictionary merge overwrite

假设我有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']}

我该如何实现?

1 个答案:

答案 0 :(得分:1)

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}}