dict.update
Tino Wildenhain
tino at wildenhain.de
Tue Sep 2 11:40:49 EDT 2008
Mike P wrote:
> 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?
result=dict((key,(dict1.get(key,None),
dict2.get(key,None)))
for key in set(dict1.keys()+dict2.keys())
)
(untested)
should provide you with a resulting dictonary with tuples
where [0] is var1 and [1] is var2, None for values not
in one of the dictionaries (you can put in 0 if you prefer).
You can use it like so to generate your output:
allitems=result.items()
allitems.sort() # sort based on keys as first tuple element
for (key,(var1,var2)) in allitems:
print key,var1,var2
HTH
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/711a3c90/attachment-0001.bin>
More information about the Python-list
mailing list