无法在嵌套字典中连接相同的键值

Failing to concatenate same key values within nested dictionary

我在 Python

中有两本词典
    my_dict1 = {
    'Country_name':{'Albania':278,'Bermuda':197,'Colombia':156},
    'student_name':{'Florida':146,'Elanie':467,'Malia': 125,'Adelina':886,'Oliva':997}
               }

    my_dict2= {
    'Country_name':{'Albania':298,'Bermuda':187,'Colombia':166},
    'student_name':{'Florida':146,'Elanie':467,'Malia': 125,'Adelina':886,'Oliva':997}
              }

预期输出为

    output = {
   'Country_name':{'Albania':[278,298],'Bermuda':[197,187],'Colombia':[156,166]},
   'student_name':{'Florida':146,'Elanie':467,'Malia': 125,'Adelina':886,'Oliva':997}
}

但是我得到的输出有一些问题,它将相同的键值替换为第二个字典值。有什么方法可以像我上面显示的那样连接这两个值吗?

我使用下面的代码行合并了它们:

def merge(f):
    def merge(a,b): 
        keys = a.keys() | b.keys()
        return {key:f(a.get(key), b.get(key)) for key in keys}
    return merge


import multipledispatch
from multipledispatch import dispatch
#for anything that is not a dict return
@dispatch(object, object)
def f(a, b):
    return b if b is not None else a
#for dicts recurse 
@dispatch(dict, dict)
def f(a,b):
    return merge(f)(a,b)

我得到的输出是

{'Country_name': {'Albania': 298, 'Bermuda': 187, 'Colombia': 166},
'student_name': {'Adelina': 886,
'Elanie': 467,
'Florida': 146,
'Malia': 125,
'Oliva': 997}}

enter code here
enter code here

您可以使用循环来更新“Country_name”(假设键在“Country_name”中的两个字典中匹配):

out = my_dict1.copy()
for k,v in out['Country_name'].items():
    out['Country_name'][k] = [v, my_dict2['Country_name'][k]]

如果其中一个国家名称不存在,我们可以使用:

out = my_dict1.copy()
for k in out['Country_name'].keys() | my_dict2['Country_name'].keys():
    a, b = out['Country_name'].get(k), my_dict2['Country_name'].get(k)
    out['Country_name'][k] = [a, b] if a and b else ([a] if not b else [b])

输出:

{'Country_name': {'Albania': [278, 298],
  'Bermuda': [197, 187],
  'Colombia': [156, 166]},
 'student_name': {'Florida': 146,
  'Elanie': 467,
  'Malia': 125,
  'Adelina': 886,
  'Oliva': 997}}