In this tutorial, you will see the technique to search keys by values in a Python dictionary. We’ll also cover how to find all keys belonging to one or more values.
While you are going through this exercise, we expect that you have a good understanding of the dictionary data structure. However, if you don’t have one, then we recommend reading the below post.
Recommended: Append to a dictionary in Python
Python Program – Search Keys in a Dictionary
The basic form of a dictionary object is as follows:
dict = {"key1": value1, "key2":value2, ...}
It is a kind of hash map which is also available in other high-level programming languages like C++ and Java.
Let’s assume that our program has a dictionary of Fortune 500 companies and their world ranking. See the below example:
# Dictionary of fortune 500 companies dictOfFortune500 = { "Walmart": 1, "Exxon Mobil" : 2, "Berkshire Hathaway" : 3, "Apple" : 4, "UnitedHealth Group" : 5, "McKesson" : 5, "CVS Health" : 5, "Amazon.com" : 6, "AT&T" : 6, "General Motors" : 7 }
Now, your task is to search for keys in the dictionary that are at world ranking 5. From the above code, you can observe that three companies are holding the 5th position.
"UnitedHealth Group" : 5, "McKesson" : 5, "CVS Health" : 5,
We’ll now see the Python code to get the list of companies ranking at the 5th position.
Also Read: Python Sorting a Dictionary
Search Keys By Value in a Dictionary
The dictionary object has an items() method which returns a list of all the items with their values, i.e., in the form of key pairs. So, we’ll call this function and then traverse the sequence to search for our desired value.
If the target value matches with some of the items in the dict
object, then we’ll add the key to a temp list.
Using For Loop
Let’s go through the below sample program that uses a for loop. It defines a searchKeysByVal()
function to search for keys in the dictionary of Fortune 500 companies.
''' Get a list of Companies from dictionary having a specfied rank ''' # Dictionary of fortune 500 companies dictOfFortune500 = { "Walmart": 1, "Exxon Mobil" : 2, "Berkshire Hathaway" : 3, "Apple" : 4, "UnitedHealth Group" : 5, "McKesson" : 5, "CVS Health" : 5, "Amazon.com" : 6, "AT&T" : 6, "General Motors" : 7 } def searchKeysByVal(dict, byVal): keysList = [] itemsList = dict.items() for item in itemsList: if item[1] == byVal: keysList.append(item[0]) return keysList ''' Get list of Companies having world raking '5' ''' keysList = searchKeysByVal(dictOfFortune500, 5) print("Fortune 500 Companies having world raking '5' are:", end = "\n\n") #Iterate over the list of companies for index, company in enumerate(keysList): print("{}: {}".format(index, company))
Output
Result... Fortune 500 Companies having world raking '5' are: 0: UnitedHealth Group 1: McKesson 2: CVS Health CPU Time: 0.03 sec(s), Memory: 8392 kilobyte(s)
Using List Comprehension
In the above code, we’ve used the Python for loop. Let’s now try achieving the same using comprehension.
''' Get the list of Companies having world ranking 5 using list comprehension ''' keysList = [company for (company, value) in dictOfFortune500.items() if value == 5] print("Fortune 500 Companies having world raking '5' are:", end = "\n\n") #Iterate over the list of companies for index, company in enumerate(keysList): print("{}: {}".format(index, company))
With the above code, we’ll get a similar result as seen before.
Search Keys By the List of Values
In this exercise, we’ll find out keys whose values match once given in the below list:
[5, 6]
To achieve this, we’ll traverse the iterable sequence, the output of the dict.items()
function. We’ll then test if the value matches with some entry from the above input list.
If this happens to be the case, then we’ll add the corresponding key to a separate list. The following code will do the needful.
''' Get the list of Companies whose rank matches with values in the input list ''' def searchKeysByValList(itemDict, valList): keysList = [] itemsList = itemDict.items() for item in itemsList: if item[1] in valList: keysList.append(item[0]) return keysList
We can call the above function by passing our dictionary of companies into it. Below is the code calling searchKeysByValList() and then there is a loop to print the companies matching our list of ranking.
''' Get the list of Companies matching any of the input values ''' keysList = searchKeysByValList(dictOfFortune500, [5, 6] ) #Iterate over the list of values for key in keysList: print(key)
Output
UnitedHealth Group McKesson CVS Health Amazon.com AT&T
Must Read: Convert Python Dictionary to JSON
Combine the Entire Code
Finally, let’s consolidate the different pieces of code so that we can see an end-to-end view of how this program searches for keys in a dictionary.
# Dictionary of fortune 500 companies dictOfFortune500 = { "Walmart": 1, "Exxon Mobil" : 2, "Berkshire Hathaway" : 3, "Apple" : 4, "UnitedHealth Group" : 5, "McKesson" : 5, "CVS Health" : 5, "Amazon.com" : 6, "AT&T" : 6, "General Motors" : 7 } ''' Get a list of Companies from dictionary having a specfied rank ''' def searchKeysByVal(dict, byVal): keysList = [] itemsList = dict.items() for item in itemsList: if item[1] == byVal: keysList.append(item[0]) return keysList ''' Get the list of Companies whose rank matches with values in the input list ''' def searchKeysByValList(itemDict, valList): keysList = [] itemsList = itemDict.items() for item in itemsList: if item[1] in valList: keysList.append(item[0]) return keysList ''' Case:1 Get list of Companies having world raking '5' ''' keysList = searchKeysByVal(dictOfFortune500, 5) print("Fortune 500 Companies having world raking '5' are:", end = "\n\n") #Iterate over the list of companies for index, company in enumerate(keysList): print("{}: {}".format(index, company)) ''' Case:2 Get the list of Companies matching any of the input values ''' keysList = searchKeysByValList(dictOfFortune500, [5, 6] ) print("\nFortune 500 Companies having world raking '5, 6' are:", end = "\n\n") #Iterate over the list of companies for index, company in enumerate(keysList): print("{}: {}".format(index, company))
Result
Fortune 500 Companies having world raking '5' are: 0: UnitedHealth Group 1: McKesson 2: CVS Health Fortune 500 Companies having world raking '5, 6' are: 0: UnitedHealth Group 1: McKesson 2: CVS Health 3: Amazon.com 4: AT&T