I have two dictionaries:
d1 = {'a':('x','y'),'b':('k','l')}
d2 = {'a':('m','n'),'c':('p','r')}
How do I merge these two dictionaries to get such result:
d3 = {'a':('x','y','m','n'),'b':('k','l'),'c':('p','r')}
This works when values of the dictionary are simple type like int or str:
d3 = dict([(i,a[i]+b[i]) for i in set(a.keys()+b.keys())])
But I have no idea how deal with lists as values...
Notice: my question is different to How to merge two Python dictionaries in a single expression? cause I don't want to update values but add them
Your question is a little bit mangled with respect to variable names, but I think this does what you want:
d3 = dict([(i,d1.get(i,())+d2.get(i,())) for i in set(d1.keys()+d2.keys())])
d3
{'a': ('x', 'y', 'm', 'n'), 'b': ('k', 'l'), 'c': ('p', 'r')}
Note that you can add (ie extend) list
s and tuples
with +
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With