-1

Can someone give me advise how to merge two dictionaries ( Beginner here) for my case . For the keys common, I want to append the values. If key is there in one and not the other dictionary, I want to add 0 as value in the merged dictionary .

d1 = {'David': '5.5', 'John': '1.0', 'Tim' : '2' }
d2 = {'David': '42.5', 'John': '37.0'}

Desired output

d3 = {'David' : ['5.5', '42.5'], 'John' : ['1.0', '37'], 'Tim' : ['2','0']}
enzo
  • 9,861
  • 3
  • 15
  • 38
Murali
  • 1

1 Answers1

2

You can iterate available keys through the set union of keys of the two dicts and for each key, output the respective values of the two dicts with the dict.get method, with 0 as a default value:

{k: [d.get(k, '0') for d in (d1, d2)] for k in d1.keys() | d2.keys()}

This returns:

{'David': ['5.5', '42.5'], 'John': ['1.0', '37.0'], 'Tim': ['2', '0']}
blhsing
  • 91,368
  • 6
  • 71
  • 106