0

How can we achieve below merge result if i have two dictionaries with different lengths with both similar and dissimilar keys .

left =  {key1: x1, key2: y1 , key3: z1 , key5 : n1}  
right = {key1: x2, key2: y2 , key4 : m1 ,key5 : n1}  

result :

d =        { key1: {x1,x2},  
             key2: {y1,y2},
             key3: {z1,missing},
             key4 :{missing,m1}
             key5 :{n1,n1}
          }
ramesh.metta
  • 139
  • 1
  • 1
  • 11

2 Answers2

4

I use square brackets (lists) instead of curly (set) because it seems that for you order is important, and sets do not preserve the order of the elements.

 keys = set(left.keys()) | set(right.keys())
 d = {}
 for k in keys:
     d[k] = [left.get(k, 'missing'), right.get(k, 'missing')]

or slightly shorter with a comprehension notation

 keys = set(left.keys()) | set(right.keys())
 d = {k: [left.get(k, 'missing'), right.get(k, 'missing')] for k in keys}
Serge
  • 3,387
  • 3
  • 16
  • 34
1

Is this what you want?

left =  {'key1': 'x1', 'key2': 'y1' , 'key3': 'z1' , 'key5' : 'n1'}  
right = {'key1': 'x2', 'key2': 'y2' , 'key4' : 'm1' ,'key5' : 'n1'}  
d=dict()

for key,val in left.items():
    d[key]=[val]
for key,val in right.items():
    if key in d.keys():
      d[key].append(val)
    else:
      d[key]=[val]

print(d)
>>>> {'key1': ['x1','x2'], 'key2': ['y1','y2'] , 'key3': ['z1'], 'key4':['m1'] , 'key5' : ['n1','n1']}  
emilaz
  • 1,722
  • 1
  • 15
  • 31
  • Hi @emilaz Thank you. can we do this way : key3: {z1,missing}, key4 :{missing,m1} because i want to track if the value is missing in left dictionary or right dictionary. for example, for key3 : right dictionary has missing value. – ramesh.metta Apr 15 '19 at 18:28
  • In that case, I would go with Serge's answer :) – emilaz Apr 15 '19 at 18:31
  • If all of the variables used in defining `left` and `right` are defined, the output would report their *values,* not the variable names. – Scott Hunter Apr 15 '19 at 19:05
  • you are correct, but it was the easiest way to give the OP the answer he was looking for. I will update my post to make it technically correct. Thanks for the heads up. – emilaz Apr 15 '19 at 19:14