dict.update

M

Mike P

Hi All,

I have two dictionaries e.g
dict1 = {123:3,234:5,456:3}
dict2 = {123:4,157:2,234:5,456:3,567:2}

I want to merge these two dictionaries together so i have a resultant
dictionary of:

dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]}

As later on i want to write a csv file that would have the form

id var1 var2
123 4 3
157 2 0

i looks like the dict.update looks almost there but i can't get it to
work properly, can anyone offer any advise?
 
D

Diez B. Roggisch

Mike said:
Hi All,

I have two dictionaries e.g
dict1 = {123:3,234:5,456:3}
dict2 = {123:4,157:2,234:5,456:3,567:2}

I want to merge these two dictionaries together so i have a resultant
dictionary of:

dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]}

As later on i want to write a csv file that would have the form

id var1 var2
123 4 3
157 2 0

i looks like the dict.update looks almost there but i can't get it to
work properly, can anyone offer any advise?

res = {}
for d in dict1, dict2:
for key, value in d.iteritems():
res.setdefault(key, []).append(value)


Diez
 
R

Raymond Hettinger

Hi All,

I have two dictionaries e.g
dict1 = {123:3,234:5,456:3}
dict2 = {123:4,157:2,234:5,456:3,567:2}

I want to merge these two dictionaries together so i have a resultant
dictionary of:

dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]}

As later on i want to write a csv file that would have the form

id      var1  var2
123     4      3
157     2      0

i looks like the dict.update looks almost there but i can't get it to
work properly, can anyone offer any advise?

The update() method is not quite right for your purposes.
But a simple generator expression will do the trick:

dict((k, [v, dict1.get(k, 0)]) for k, v in dict2.items())
{456: [3, 3], 234: [5, 5], 123: [4, 3], 157: [2, 0], 567: [2, 0]}


Raymond
 
M

Mike P

Thanks Diez,

This is almost perfect!

Is there a way to ensure each list has two elements, even if one of
them is blank?

Mike
 
M

Mike P

Thanks Raymond,

That's a neat trick, i'll look into learning more about this

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,781
Messages
2,569,616
Members
45,306
Latest member
TeddyWeath

Latest Threads

Top