I have a simple question about getting a key corresponding to a specific value in a dictionary in python. Please note I need only one command or one method(). No for loop, no writing def code, no map, or lambda etc., if there is a straightforward method() or command, please respond. If such a command does not exist in python, please create it and add it to the library. I suggest something like dic_inverse[value] or dic.inv(value) for the name of such a command.
Example: how to return the key corresponding to one specific value = 20 by one simple, clear, nice method() or command?
dict = {'age': 20, 'height' : 154}
dict_inverse[20] = ????
or dict.inverse(20) = ????
CodePudding user response:
Creating and Looking up an inverse dict is as simple as it gets. You can abstract it into a function and pass in the dict and value to make your code cleaner.
def lookup_by_val(d, val)
inverse_dict = {v: k for k, v in d.items()}
return inverse_dict[val]
P.S. You might wanna add error handling if you are not sure that input is not safe.
CodePudding user response:
I'm sure you are talking about Enum
. Make sure that the values are always unique, otherwise it will only return the first key associated with that value.
Initializing Enum
First, you can initialize your Enum by setting up a class that inherits from the class Enum
.
from enum import Enum
class Person(Enum):
age = 20
height = 154
Accessing Keys and Values
Then, you can get the corresponding value from a key.
>>> print(Person.age.value)
20
Or you can do it backward, getting the key from a value.
>>> print(Person(154).name)
height