Reputation: 39
I am working on a program where I have a dictionary dict['key'] = value
, but I would also like to be able to use dict['value']
and have it return the key
.
Are there any reversible data structures like this in Python?
I was thinking of adding all of the opposites to my dictionary because all of my relations are 1:1, but I don't think that would be as efficient because I would have twice as many entries as I need.
Upvotes: 2
Views: 72
Reputation: 311458
I'm not aware of any bidirectional map in python's standard collection library, but you can take a look at the bidict package:
>>> from bidict import bidict
>>> b = bidict(k='v')
>>> b['k']
'v'
>>> b.inv['v']
'k'
Upvotes: 3
Reputation: 16184
For a single-reverse lookup like this, just use
[k for k in dict if dict[k] == v]
If you use this back-tracking usually, the common way to do it would be to create a reverse dictionary (note that in that case more than one key per value will result in lossy process) -
rev_dict = {v: k for k, v in dict.items()}
Finally, you might also consider handling your data as tuples of length 2 - like
data = [(a, b), (c, d)]
if one item does not depend on the other.
Upvotes: 2