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, then we recommend reading the below post.
Append to a dictionary in Python
The basic form of a dict object is as follows:
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 keys in the dictionary which are at world ranking 5. From the above code, you can observe that there are three companies 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.
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 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.
Sample code
''' 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)In the above code, we’ve used the Python for loop. Let’s now try achieving the same using the 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 in a dictionary by the list of values
In this exercise, we’ll find out keys whose value are matching once given in below list:
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 it 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 keysListWe 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&TCombine the entire code
# 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))Output
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