join dictionaries using keys from one & values

bonono at gmail.com bonono at gmail.com
Mon Dec 5 23:42:33 EST 2005


ProvoWallis wrote:
> I'm still learning python so this might be a crazy question but I
> thought I would ask anyway. Can anyone tell me if it is possible to
> join two dictionaries together to create a new dictionary using the
> keys from the old dictionaries?
>
> The keys in the new dictionary would be the keys from the old
> dictionary one (dict1) and the values in the new dictionary would be
> the keys from the old dictionary two (dict2). The keys would be joined
> by matching the values from dict1 and dict2. The keys in each
> dictionary are unique.
>
> dict1 = {1:'bbb', 2:'aaa', 3:'ccc'}
>
> dict2 = {5.01:'bbb', 6.01:'ccc', 7.01:'aaa'}
>
> dict3 = {1 : 5.01, 3 : 6.01, 2 : 7.01}
>
> I looked at "update" but I don't think it's what I'm looking for.
>
> Thanks,
If you can be sure that the value is hashable, I think you can just
invert one of the dict(key/value flipped) and a for loop to create the
new dict

dict2x = dict( ((dict2[k], k) for k in dict2.iterkeys()))
dict3 = dict(((k, dict2x[v]) for k,v in dict1.iteritems()))

This doesn't handle the case where v is in dict1 but not in dict2, it
can be filtered out though.




More information about the Python-list mailing list