searching dictionary by value in python

The following list comprehension is a life saver for me to search a dictionary by value. Searching dictionary by value may not seem to be sensible as you may get multiple values but in case needed, it is a wonderful one line of code.

list_values = [ key for key,val in mydict.items() if val==value ]

Here we take the ‘value’, iterate through the mydict dictionary and if any dictionary member is found having this value, then we grab the key value and assign them to the list ‘list_values’ . It may return for example 10 keys all of which can be accessed via the list assigned. It is a spectacular structure and I wanted to take a note here to reference later:)

About: rtoodtoo

Worked for more than 10 years as a Network/Support Engineer and also interested in Python, Linux, Security and SD-WAN // JNCIE-SEC #223 / RHCE / PCNSE


You have a feedback?

Discover more from RtoDto.net

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

Continue reading