TAGS :Viewed: 17 - Published at: a few seconds ago

[ How do I map values to values with a common key in Python ]

In the dictionaries below I want to check whether the value in aa matches the value in bb and produce a mapping of the keys of aa to the keys of bb. Do I need to rearrange the dictionaries? I import the data from a tab separated file, so I am not attached to dictionaries. Note that aa is about 100 times bigger than bb (100k lines for aa), but this is to be run infrequently and offline.

Input:

aa = {1: 'a', 3: 'c', 2 : 'b', 4 : 'd'}
bb = {'apple': 'a', 'pear': 'b', 'mango' : 'g'}

Desired output (or any similar data structure):

dd = {1 : 'apple', 2 : 'pear'}

Answer 1


aa = {1:'a', 3:'c', 2:'b', 4:'d'}
bb = {'apple':'a', 'pear':'b', 'mango': 'g'}

bb_rev = dict((value, key)
    for key, value in bb.iteritems()) # bb.items() in python3
dd = dict((key, bb_rev[value])
    for key, value in aa.iteritems() # aa.items() in python3
    if value in bb_rev)

print dd

Answer 2


You can do something like this:

>>> aa = {1: 'a', 3: 'c', 2 : 'b', 4 : 'd'}
>>> bb = {'apple': 'a', 'pear': 'b', 'mango' : 'g'}
>>> tmp = {v: k for k, v in bb.iteritems()}
>>> dd = {k: tmp[v] for k, v in aa.iteritems() if v in tmp} 
 >>> dd
{1: 'apple', 2: 'pear'}

but note that this will only work if each value of the aa dictionary appears as a value of the bb dictionary either once or not at all.