Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of values of two dictionaries merged by key


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

like image 276
psmith Avatar asked Jun 27 '15 21:06

psmith


1 Answers

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) lists and tuples with +.

like image 181
xnx Avatar answered Sep 17 '22 06:09

xnx