Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get dict key for matching value in unique values?

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading