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 code above handles duplicate values; inverted[v] returns a list of keys that hold this value.
If your values ββare also unique, you can use a simple dict instead of defaultdict :
inverted = { v: k for k, v in dictionary.iteritems() }
or, in python 3, where items() is a dictionary:
inverted = { v: k for k, v in dictionary.items() }
Martijn Pieters Sep 21 '12 at 9:25 AM 2012-09-21 09:25
source share