How to find all keys in a dictionary with a given value in python ?

Active March 24, 2021    /    Viewed 1738    /    Comments 0    /    Edit


Examples of how to find in python all keys in a dictionary with a given value:

Create a dictionary

Let's create a simple dictionary:

d = {'George Chandler': 20,
 'Scott Respess': 25,
 'Chelsea Pineda': 25,
 'Carmen Wright': 25,
 'Lillian Hirsch': 21,
 'Nathaniel Chipman': 21,
 'Gladys Patterson': 22,
 'Nicholas Mccanna': 21,
 'Dwight Mccullough': 22,
 'Charles Stanley': 23}

key is the full name and value the age here.

Find all keys in a dictionary with a given value using a loop

To find all users of 21 year old from the dictionary d, a solution is to iterate over the entire dictionary:

for k,v in d.items():
        if v == 21:
                print('{} has 21'.format(k))

returns

Lillian Hirsch has 21
Nathaniel Chipman has 21
Nicholas Mccanna has 21

Create a list of all keys in a dictionary with a given value

We can also create a list of users of 21 year old:

[k for k,v in d.items() if v == 21]

returns

['Lillian Hirsch', 'Nathaniel Chipman', 'Nicholas Mccanna']

Additionnal solutions

Another solution that works if the value is unique:

d = {'George Chandler': 20,
 'Scott Respess': 25,
 'Chelsea Pineda': 25,
 'Carmen Wright': 25,
 'Lillian Hirsch': 21,
 'Nathaniel Chipman': 21,
 'Gladys Patterson': 22,
 'Nicholas Mccanna': 21,
 'Dwight Mccullough': 22,
 'Charles Stanley': 23}

list(d.keys())[list(d.values()).index(21)]

returns

'Lillian Hirsch'

If the value is not unique, a solution is to use itemgetter

from operator import itemgetter

itemgetter(*[idx for idx,e in enumerate(list(d.values())) if e == 21])(list(d.keys()))

returns

('Lillian Hirsch', 'Nathaniel Chipman', 'Nicholas Mccanna')

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount