giova.deicco
giova.deicco

Reputation: 11

How to merge 2 dictionaries in Python by single value

I want to merge these dictionaries:

d1 = {'r1':[100,200,300],'r2':[400,500]}
d2 = {100:[110,120,130],200:[210,220],300:[310,320],400:[410,420],500:[510,520]}

like this:

d3 = {'r1':[100,[110,120,130],200,[210,220],300,[310,320]],'r2':[400,[410,420],500, [510,520]]}

How can I do this?

Upvotes: 0

Views: 171

Answers (4)

CT Zhu
CT Zhu

Reputation: 54380

In [102]:

import itertools
{k:list(itertools.chain(*zip(item, map(d2.get, item)))) for k, item in d1.items()}
Out[102]:
{'r1': [100, [110, 120, 130], 200, [210, 220], 300, [310, 320]],
 'r2': [400, [410, 420], 500, [510, 520]]}

Upvotes: 0

Ryan Haining
Ryan Haining

Reputation: 36882

I like this problem.

>>> d3 = {k: [a for i in v for a in (i, d2[i])] for k, v in d1.items()}
>>> d3
{'r1': [100, [110, 120, 130], 200, [210, 220], 300, [310, 320]], 'r2': [400, [410, 420], 500, [510, 520]]}

eveyone seems to be off by just a little bit from your desired output, but this looks like a match to me.

It's a pretty nested use of list comprehensions and dict comprehenions.

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208565

d3 = {}
for k, v in d1.items():
    new_v = []
    for k2 in v:
        new_v.append(k2)
        new_v.append(d2.get(k2, []))
    d3[k] = new_v

Upvotes: 0

fabmilo
fabmilo

Reputation: 48330

dict( (k, v + [ d2[k2] for k2 in v if k2 in d2 ]) for k,v in d1.iteritems())

Upvotes: 0

Related Questions