A pretty basic question, but was really unable to find it on the Internet…
What’s the most pythonic way to get the key that belongs to a list of values of which the input arg is an element?
I am under the impression that dict might not be the right type. Reason why I would chose it is that both all they keys, as well as all the values are unique. –> It’s some form of "unique alias mapping", which is why the inversion value -> key should work.
my_dict = {
'key1': ['a', 'b', 'c'],
'key2': ['d', 'e'],
'key3': ['f'],
'key4': 'g'
}
identifier = 'a'
# Desired output: the following functional call works
my_dict.get_key_from_value_in_value_list(identifier)
'key1'
>Solution :
If, as you stated, all the values are unique you can create an inverse dictionary and use this for lookup:
my_dict = {"key1": ["a", "b", "c"], "key2": ["d", "e"], "key3": ["f"], "key4": "g"}
inv_dict = {v: k for k, l in my_dict.items() for v in l}
print(inv_dict['a'])
Prints:
key1