Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Opposite of dictionary search [duplicate]

>>>Dictionary[key]

The above statement returns the first corresponding value of the 'key' from the 'Dictionary' but is there a function that does the opposite, i.e. search for the key by it's value

like image 413
Taher Elhouderi Avatar asked Jul 29 '26 20:07

Taher Elhouderi


1 Answers

You can write simple lambda for this:

d={"a":5, "bf": 55, "asf": 55}

search_key = lambda in_d, val: (k for k,v in in_d.items() if v == val)

for k in search_key(d, 55):
    print(k)

# since the lambda returns generator expression you can simply print
# the keys as follows:

print(list(search_key(d, 55)))  
# or get the key list
key_list = list(search_key(d, 55))

Gives:

asf
bf
like image 145
Marcin Avatar answered Aug 01 '26 11:08

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!