简体   繁体   中英

how to retrieve all keys with a given value from dictionary in python

I want to get the list of keys of dictionary for a given value. For example

my_dict = {1: 2, 3: 3, 4: 2}
value = 2

I want to get 1 and 4.

How to get the list of correspondent keys?

Using list comprehension you can filter per values as well as per keys:

given_value = 2
keys_list = [k for k, v in my_dict.items() if v == given_value]  # [1, 4]

Or using Python built-in filter :

given_value = 2
keys_iter = filter(lambda k: my_dict[k] == given_value, my_dict.keys()) # return an iterator
keys_list = list(keys_iter)

A list comprehension can do that in linear time - if you need that once. If your design needs for alternating retrieving keys -> values and values->keys mappings , them you can design your own class or by using a library.

My own Python's Extradict has the BijectiveDict class that does exactly that, trying to be as direct as possible.

But note that you need to further specify your desired behavior there - in your example, the value 2 is associated with 2 keys. BijectiveDict's default behavior is to simply overwrite the earlier assignments: you jsut retrieve the latest key bound to a certain value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM