TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Search Keys by Value in a Dictionary
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Search Keys by Value in a Dictionary

Last updated: Apr 16, 2024 1:56 am
By Meenakshi Agarwal
Share
8 Min Read
Search keys by values in a Python dictionary
Search keys by values in a Python dictionary
SHARE

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.

Contents
Search Keys By Value in a DictionaryUsing For LoopUsing List ComprehensionSearch Keys By the List of ValuesCombine the Entire CodeResult

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

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Various Python for loop example Python For Loop Examples
Next Article Python range function explained Python Range() Function

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x