0

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?

3
  • 1
    You should try writing some code to do this. If and when you run into problems, ask a specific question, providing simple code to reproduce the problem. This isn't a code writing service. Commented Apr 23, 2014 at 17:03
  • or better yet, define the problem. this isn't merge. this is how can i add the values for keys from a second dictionaries into lists which are values of the first dictionary. when the values should be added right after the location of the key from d2 in the list that is a value of d1. or more importantly - why would you want to
    – vish
    Commented Apr 23, 2014 at 17:07
  • Thanks a lot :) I'm an absolute beginner.. Commented Apr 23, 2014 at 17:35

4 Answers 4

1

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.

0
0
dict( (k, v + [ d2[k2] for k2 in v if k2 in d2 ]) for k,v in d1.iteritems())
0
0
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
0
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]]}

Not the answer you're looking for? Browse other questions tagged or ask your own question.