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!
答案 0 :(得分: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']}
答案 1 :(得分: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']}