Combining 2 dictionaries with common key
All you need to do is to modify append
to extend
which will then add the elements of the list rather than adding the list itself. See the list
docs for more details on the difference between append
and extend
.
dict1 = {'key1':['value11','value12','value13'] , 'key2':['value21','value22','value23']}
dict2 = {'key1':['value14','value15'] , 'key2':['value24','value25']}
dict3 = {}
for key in set().union(dict1, dict2):
if key in dict1: dict3.setdefault(key, []).extend(dict1[key])
if key in dict2: dict3.setdefault(key, []).extend(dict2[key])
print(dict3)
# {'key2': ['value21', 'value22', 'value23', 'value24', 'value25'], 'key1': ['value11', 'value12', 'value13', 'value14', 'value15']}
Alternatively you could use a collections.defaultdict
with the default set to list
as shown below.
from collections import defaultdict
dict3 = defaultdict(list)
for key in set().union(dict1, dict2):
for dic in [dict1, dict2]:
if key in dic:
dict3[key] += dic[key]
You can do it much simpler but if you want to use your code just change append
to extend
dict1 = {'key1':['value11','value12','value13'] , 'key2':['value21','value22','value23']}
dict2 = {'key1':['value14','value15'] , 'key2':['value24','value25']}
dict3 = {}
for key in (dict1.viewkeys() | dict2.keys()):
if key in dict1: dict3.setdefault(key, []).extend(dict1[key])
if key in dict2: dict3.setdefault(key, []).extend(dict2[key])
print dict3
output:
{'key2': ['value21', 'value22', 'value23', 'value24', 'value25'], 'key1': ['value11', 'value12', 'value13', 'value14', 'value15']}
You can read this post about the difference ov append to extend