1

I have two dictionaries:

dict1 = { 'url1': '1', 'url2': '2', 'url3': '3', 'url4': '4' }
dict2 = { 'url1': '1', 'url2': '2', 'url5': '5', 'url6': '6' }

and wanted to merge them to come up with a dict that looks like this:

dict_merged = { 'url1': ['1','1'], 'url2': ['2','2'], 'url3': ['3','0'], 'url4': ['4','0'], 'url5': ['0','5'], 'url6': ['0','6'] }

I already have the following code to merge both but how do I assign the default value '0' if the key is not found in one of the dicts?

dict_merged = dict()
for key in (dict1.keys() | dict2.keys()):
    if key in dict1:
        merged.setdefault(key, []).append(dict1[key])
    if key in dict2:
        merged.setdefault(key, []).append(dict2[key])

Thanks in advance!

F. Elliot
  • 71
  • 6
  • Possible duplicate of [Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?](https://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe) – mrhallak Jun 15 '17 at 10:15

2 Answers2

4

Use dict.get to return the default value. You can then easily use a dict comprehension and don't need to test for membership:

m = {k: [dict1.get(k, '0'), dict2.get(k, '0')] for k in dict1.keys()|dict2.keys()}
print(m)
# {'url4': ['4', '0'], 'url3': ['3', '0'], 'url1': ['1', '1'], 'url6': ['0', '6'], 'url5': ['0', '5'], 'url2': ['2', '2']}
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

A variety of @Moses Koledoye's answer using set().union():

a = {k: [dict1[k] if k in dict1 else '0', dict2[k] if k in dict2 else '0'] for k in set().union(*(dict1, dict2))}
print(a)

>>> {'url1': ['1', '1'],
    'url2': ['2', '2'],
    'url3': ['3', '0'],
    'url4': ['4', '0'],
    'url5': ['0', '5'],
    'url6': ['0', '6']}
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43