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

Published: March 24, 2021

Tags: Python; Dictionary;

DMCA.com Protection Status

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