Just create an inverted mapping:
from collections import defaultdict
inverted = defaultdict(list)
for k, v in dictionary.iteritems():
inverted[v].append(k)
Note that the above code handles duplicate values; inverted[v]
returns a list of keys that hold that value.
If your values are also unique, a simple dict can be used instead of defaultdict
:
inverted = { v: k for k, v in dictionary.iteritems() }
or, in python 3, where items()
is a dictionary view:
inverted = { v: k for k, v in dictionary.items() }