Python Dictionary Find Key By Value

In this Python tutorial, you will learn about Python dictionaries to find keys by value. This concept is less implemented or quite opposed to getting the values by key concepts.

However, I have provided several examples of how implementing these concepts in your project can benefit you.

One example is getting the product name based on the value, which means the product name is stored as a key, and its type is stored as a value in the dictionary.

So, let’s start,

Python Dictionary Find Key By Value

To find the dictionary key by value, you can use several methods, such as the loop, dictionary comprehension, and filter().

Python Dict Find Key By Value Using Loop

You can use the loop to find the key by value here. You need to iterate over the dictionary, grab the value, and compare it with the value whose key you want to extract.

In simpler words, this method involves iterating over all the key-value pairs in the dictionary and checking if the current value matches the desired value.

If a match is found, the corresponding key is returned. If the loop completes without finding a match, None (or some other default value) is returned to indicate that no key was found for the given value.

For example, you manage a user database where each user has a role such as ‘admin’ or ‘user’. All the user’s data are stored in the dictionary named ‘users’; you need to find all the users who are admins.

Let’s simulate the dictionary ‘users’ by creating it using the code below.

users = {
	'Roy': 'admin',
	'Ralph': 'user',
	'Philip': 'admin',
	'Russell': 'user'

Use the code below to iterate over the dictionary ‘user’ and grab the key value by calling the items() function on the dictionary with a for loop.

for key, value in users.items():
  if value =='admin':
Python Dict Find Key By Value Using  Loop

The code output in the above picture shows two users, Roy and Philip, who are designated as ‘admin’. Here, the user’s name is key in the dictionary ‘users’, and these are found by the value ‘admin’.

Understand the code part ‘for key values in users.items():’ This part iterates over the dictionary and grabs the object key-value pair as a tuple using the items() function on the dictionary.

READ:  Constructor in Python [Complete Guide]

Then, it grabs the value from each pair in each iteration and compares that value with the specified value (‘admin’) using the if value ==’admin’:; if the specified value matches the value in the dictionary, it prints the corresponding key.

As a result, you get the key by value.

Python Get Key By Value Using the Dictionary Comprehension

Dictionary comprehension is a short way to create a new dictionary based on the existing dictionary by iterating over it within the curly braces {}.

You must read this Python dictionary comprehension [7 methods] to know more about dictionary comprehension.

For example, you are building a feature for your e-commerce website that displays product information on the pages by their price ranges. In that case, you can filter all the products based on the price.

The product data is stored in the ‘products’ dictionary, where the product’s name is a key and its price is a value, as shown below.

products = {
	'T-shirt': 19.99,
	'Jeans': 39.99,
	'Sneakers': 59.99,
	'Shorts': 19.99, 
	'Jacket': 39.99,
	'Boots': 59.99,
	'Hat': 19.99, 
	'Socks': 19.99, 
        'Belt': 39.99,
	'Scarf': 19.99

Apply the dictionary comprehension concepts as shown in the code below.

product_name={key for key,value in products.items() if value == 19.99}
Python Get Key By Value Using the Dictionary Comprehension

From the output, you can see the products priced at 19.99 are {‘Socks’, ‘Scarf’, ‘Shorts’, ‘T-shirt’, ‘Hat’}. Here, the price is the value of the dictionary; the product name is the key.

So, the key (product name) is extracted from the dictionary using the value (price).

Let’s understand this part of the code: product_name= {key for key, value in products.items() if value == 19.99}, divide this code into three parts to understand it easily.

First is the loop part for key, value in products.items():, it extract all the key-pair of the dictionary using the items() function on the dictionary.

Then this part, if value == 19.99, compares each value with the specified value (price); if it is true or a match is found, then it adds the corresponding key to the dictionary proudcts_name by selecting the ‘key’ as the first value in the dictionary.

As a result, it returns all the dictionary keys by matching the specified value.

Get Key By Value Python Using the filter() Function

The filter() is a function in Python that returns the list of items based on the given condition and iterator. After understanding the filter, I will show you how to use the filter to get the dictionary key by value.

READ:  PdfFileWriter Python Examples (20 examples)

The syntax for using the filter is given below.

filter(function, iterator)


  • function: It is the argument that represents the function, and this function is executed for each item in the iterator.
  • Iterator: It is the group of items or collections, such as a list or dictionary, on which the function is expected to test a condition, and then matched condition-based items are returned.

For example, suppose you have a list of numbers, as shown in the code below.

numbers=[4, 3, 5, 8, 12, 67, 8]

Also, there is a function named specific_data that returns only the values less than 15 in the list, as shown in the code below.

def specific_data(x):
  if x > 15:
    return False
    return True

To test the function for each value in the ‘numbers’ list, pass the function and list of values to the filter() function as shown in the code below.

data = filter(specific_data, numbers)
for value in data:
Understand Filter() Before Get Key By Value Python Using the filter() Function

Look, all the returned list of values are smaller than 15, so here, the function ‘spcific_data’ is executed for each value in the list ‘numbers’ to check whether the current value is greater than 15. If it is, then ignore it. Otherwise, it is smaller. Add it to the list to return as a result.

Similarly, you will create a function that checks for matching values in the dictionary. If a value matches, it will return the corresponding key.

So here, we will use the another kind of function called lamda which is also called anonymous function, it takes any number of argument and only one condtion or the expression which you wan to evaluate.

let me also show you how the lambda function works; the syntax is below.

function_name = lambda arguments:expression


  • function_name: Name the function you will use to call with values.
  • lambda arguments: The lambda keyword is followed by the arguments equal to those you provide in a normal function like (x, Y).
  • expression: The one line of expression you want to evaluate to something like x+y.

For example, you can create a function using the lambda to sum two numbers, as shown below.

add = lambda x, y: x+y
print(add(3, 5))
Understand Lambda Function Before Get Key By Value Python Using the filter() Function

Look at the lambda function add sums the two numbers 3 and 5 returns 8. Here lambda x, y: x=y. The keyword lambda is specified with two arguments that it accepts: x and y. The expression x + y means add the y to the x.

READ:  KeyError in a nested Python dictionary

Now that you know how filter() and the lambda function work, let’s return to the topic of getting key by value.

Suppose you have to create a function that returns all the products of a specific type using the filter() methods. For that, you can access the dictionary named ‘inventory’, shown below.

inventory = {
	'tomato': 'vegetable',
	'pear': 'fruit',
	'lettuce': 'vegetable',
	'peach': 'fruit',
	'potato': 'vegetable',
	'grape': 'fruit'

In the above dictionary ‘inventory’, contains the key which is the name of the product and value which is the category of the product.

For example, suppose you need to find a fruit-type product. You can use the filter(), as shown in the code below.

type = 'fruit'

product_keys = list(filter(lambda product: inventory[product] == type, inventory))

Get Key By Value Python Using the filter() Function

Look the output, the product name which is the key is returned [‘pear’, ‘peach’, ‘grape’] based on the specified type ‘fruit’ which is the value.

Let’s understand the code part and list(filter(lambda product: inventory[product] == type, inventory)). Here, the lambda function and dictionary ‘inventory’ are passed to the filter function, where the function is executed on each dictionary item.

lambda product: inventory[product] == type, inventory, this part of the filter() function, takes the product as the argument, which is the key in the ‘inventory’ dictionary. Using the expression inventory[product] == type, it checks if the value of that key is equal to ‘type’. If it is, then return True; otherwise, return false.

Overall, the filter function iterates over the dictionary keys and applies the function to each key. Then, it takes only the keys from the dictionary whose values match the specified ‘type’, which is fruit.

Then, the result of the filter() function is converted into a list of keys using Python’s list() constructor, which is the usual process of converting the result of the filter() into a list.

Finally, the list contains all the filtered keys assigned to the ‘product_keys’ variable. As a result, you get the key by value using the filter() function.

I hope that the above examples help you understand how to find a key from a value in a dictionary in Python.


In this Python tutorial, you learned about Python dictionaries to find keys by value using the for loop, dictionary comprehension and filter().

Additionally, you learned how filter() and lambda function works from scratch.

You may like to read: