join dictionaries using keys from one & values

Devan L devlai at gmail.com
Tue Dec 6 00:35:46 EST 2005


ProvoWallis wrote:
> Thanks so much. I never would have been able to figure this out on my
> own.
>
> def dictionary_join(one, two):
>
>      dict2x = dict( ((dict2[k], k) for k in dict2.iterkeys()))
>      dict3 = dict(((k, dict2x[v]) for k,v in dict1.iteritems()))
>      print dict3
>
> dict1 = {1:'bbb', 2:'aaa', 3:'ccc'}
>
> dict2 = {'5.01':'bbb', '6.01':'ccc', '7.01':'aaa'}
>
> dictionary_join(dict1, dict2)

You might want to make a working function.

def join_dicts(d1,d2):
    temp = dict(((d2[k], k) for k in d2.iterkeys()))
    joined = dict(((k, temp[v]) for k,v in d1.iteritems()))
    return joined




More information about the Python-list mailing list