Build a dictionary to search for a key by value

Dictionary

usually good for finding a value by key, but finding a key by value is rather slow

for k,v in dictionary.items(): if v = myValue: return k 

is there already a data structure that does both key-> value and ke

+2
python
21 Sept '12 at 9:22
source share
3 answers

You can try bidict :

 >>> husbands2wives = bidict({'john': 'jackie'}) >>> husbands2wives['john'] # the forward mapping is just like with dict 'jackie' >>> husbands2wives[:'jackie'] # use slice for the inverse mapping 'john' 
+8
Sep 21 '12 at 9:24
source share

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() } 
+5
Sep 21 '12 at 9:25
source share

Python 3:

 revdict = {v:k for k,v in dictionary.items()} 

(use .iteritems() instead of Python 2)

0
Sep 21 '12 at 9:27
source share



All Articles