In dictionaries, in Python, is it possible to access a key through the value? Is there any method that invert key / value?
In dictionaries, in Python, is it possible to access a key through the value? Is there any method that invert key / value?
dict
has no native method for this. But there is a maneuver that can be done.
You can use the values
method, which returns a list
. Then you get the index from that list and get the values from the other list generated by the keys
method.
Confused? So let's take an example:
valores = {"valor_16" : 16, "valor_17" : 17}
valores.keys()[valores.values().index(16)]; // "valor_16"
Original answer on SOEN