How do i search for a key in python?

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:

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 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:

[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 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  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

Combine 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

How do you get a specific key in Python?

Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.

How do I find the value of a key?

get() to get the default value for non-existent keys. You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

How do you check if a key exists in a dictionary Python?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do I find a key

To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.