Home > Software engineering >  Failing to concatenate same key values within nested dictionary
Failing to concatenate same key values within nested dictionary

Time:04-06

I have two dictionaries in 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}
              }

Expected output is

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

But the output that I have got has some issues it replaces the same key values with the second dictionary values. Is there any way to concatenate these two values as I have shown above?

and I merged them using the below lines of code:

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)

The output that I have got is

{'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

CodePudding user response:

You could use a loop to update "Country_name" (assuming the keys match across the two dicts in "Country_name"s):

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

If there is a country name that doesn't exist in one or the other, we could use:

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])

Output:

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