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

Genco has worked for more than 10 years as a Network/Support Engineer. He is also interested in Python, Linux, Security and SD-WAN, currently lives in the Netherlands and works as a Network Support Engineer at Tesla Inc. // JNCIE-SEC #223 / RHCE / PCNSE


You have a feedback?

This site uses Akismet to reduce spam. Learn how your comment data is processed.