Close Menu
TechBeamersTechBeamers
    TechBeamersTechBeamers
    • Python
    • Java
    • C
    • SQL
    • MySQL
    • Selenium
    • Testing
    • Agile
    • Linux
    • WebDev
    • Technology
    TechBeamersTechBeamers
    Python Examples

    Search Keys by Value in a Dictionary

    By Meenakshi AgarwalUpdated:Nov 05, 2023No Comments6 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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

    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.

    Python Program – Search Keys in a Dictionary

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

    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.

    See also  Essentials of Python Socket Programming

    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

    Let’s go through the below sample code. It defines a searchKeysByVal() function for the purpose of searching for keys in a 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)

    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 in a dictionary 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.

    See also  Python Sorted() Function

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

    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
    Previous ArticlePython For Loop Examples
    Next Article Python Range() Function
    Meenakshi Agarwal

    I'm Meenakshi Agarwal, founder of TechBeamers.com, with 10+ years of experience in Software development, testing, and automation. Proficient in Python, Java, Selenium, SQL, & C-Sharp, I create tutorials, quizzes, exercises and interview questions on diverse tech topics. Follow my tutorials for valuable insights!

    Add A Comment

    Leave A Reply Cancel Reply

    Python Coding Exercises for Beginners
    • 40 Python Exercises for Beginners
    • 6 Python Data Class Exercises
    • 100+ Python Interview Questions for 2024
    • 20 Python Programs to Print Patterns
    Python Basic Tutorials
    • Python Keyword
    • Python Statement
    • Python Comment
    • Python Data Types
    • Python String Methods
    • Python Multiline Strings
    • Python Split Strings
    • Python Slice Strings
    • Iterate Strings in Python
    • Python String Format
    • Python String Concatenation
    • Python Permutations of a String
    • Python Numbers
    • Python List
    • Python List Reverse
    • Python List Slice
    • Python Nested List
    • Python Set
    • Python Tuple
    • Python Dictionary
    • Python Dict to JSON
    • Python Dictionary Examples
    • Python OrderedDict
    • Python Arrays
    • Python Generate SubArrays
    • Python Heapq (Heap queue)
    • Python Operators
    • Python XOR Operator
    • Operator Precedence
    • Python Namespace
    • Python For Loop
    • Python While Loop
    • Python If Else
    • Python Switch Case
    • Python Function
    • Higher Order Functions in Python
    • Python Class
    • Python Class Definition
    • Python Data Class
    • Python Inheritance
    • Python Multiple Inheritance
    • Python Static Method
    • File Handling in Python
    • Python Copy File
    • Python Exception Handling
    • Python Try Except
    • Python Lambda
    • Python Generator
    • Python Module
    Python Pandas in Action
    • Rename Columns using Pandas
    • Python Pandas to Read CSV Files
    • Python Pandas to Merge CSV Files
    • Python Dictionary to DataFrame
    • Python Find Length of List
    Python Important Functions
    • Python Glob()
    • Python Range()
    • Python Float Range()
    • Python Map()
    • Python Filter()
    • Python Enumerate()
    • Python Zip()
    • Python Join()
    • Python Ord()
    Python Advanced Tutorials
    • Python Multithreading
    • Python Socket Programming
    • Selenium Python
    • Python Unittest
    • Python Time Module
    • Python Datetime
    • Python IRC
    • PyLint in Python
    • Python Random Number
    • Python MongoDB
    • Python Pickle
    Python Code Examples
    • Python List Contains Elements
    • Python Search Dictionary by Value
    • Python Check Type of Variable
    • Python Check Version Using Code
    • Python Loop Through Files
    • Compare Strings in Python
    • Replace Strings in Python
    • Size of Integer in Python
    • Simple Socket in Python
    • Threaded Socket in Python
    Python Tips & Tricks
    • 30 Essential Python Tips
    • 10 Python Coding Tips
    • 12 Python Code Optimization Tips
    • 10 Python Programming Mistakes
    Python General Topics
    • Top 10 Python IDEs
    • Top 7 Python Interpreters
    • Top 7 Websites for Python
    • Top 5 Chrome Plugin for Python
    Python Quizzes - General
    • Python Quiz-1
    • Python Quiz-2
    • Python Quiz-3
    • Python Quiz-4
    Python Quizzes - Advanced
    • Python Quiz - Data Structures
    • Python Quiz - Threads
    • Python Quiz - DA
    Python MCQ - Strings
    • Python MCQ Strings-1
    • Python MCQ Strings-2
    Python MCQ - Classes `
    • Python MCQ Classes-1
    • Python MCQ Classes-2
    Python MCQ - Functions
    • Python MCQ Functions-1
    • Python MCQ Functions-2
    Python MCQ - File I/O
    • Python MCQ File I/O-1
    • Python MCQ File I/O-2
    Latest Posts
    • 30 Python Programming Questions On List, Tuple, and Dictionary
    • 4 Different Ways to Rename Columns in Pandas
    • 4 Unique Ways to Reverse a String in Python
    • 40 Google Interview Questions You Need to Join Google in 2023
    • 40 Python Exercises for Beginners
    • 44 Python Data Analyst Interview Questions
    • 7 Websites to Learn Python Programming

    Subscribe to Updates

    Get the latest tutorials from TechBeamers.

    Loading
    • About
    • Contact
    • Disclaimer
    • Privacy Policy
    • Terms of Use
    © 2023 TechBeamers. All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.