Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Count keys with particular value in dictionary
Next article icon

Python | Count keys with particular value in dictionary

Last Updated : 15 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it's occurrence. Let's discuss certain ways in which this problem can be solved. 

Method #1: Using loop This problem can be solved using naive method of loop. In this we just iterate through each key in dictionary and when a match is found, the counter is increased. 

Python3
# Python3 code to demonstrate working of # Count keys with particular value in dictionary # Using loop  # Initialize dictionary test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}  # printing original dictionary print("The original dictionary : " +  str(test_dict))  # Initialize value  K = 2  # Using loop # Selective key values in dictionary res = 0 for key in test_dict:     if test_dict[key] == K:         res = res + 1      # printing result  print("Frequency of K is : " + str(res)) 

Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2: Using sum() + values() This can also be solved using the combination of sum() and value(). In this, sum is used to perform the summation of values filtered and values of dictionary are extracted using values() 

Python3
# Python3 code to demonstrate working of # Count keys with particular value in dictionary # Using sum() + values()  # Initialize dictionary test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}  # printing original dictionary print("The original dictionary : " +  str(test_dict))  # Initialize value  K = 2  # Using sum() + values() # Selective key values in dictionary res = sum(x == K for x in test_dict.values())      # printing result  print("Frequency of K is : " + str(res)) 

Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #3 : Using count() and values().These methods can be used together to find number of keys with particular value.

Python3
# Python3 code to demonstrate working of # Count keys with particular value in dictionary # Using count() + values()  # Initialize dictionary test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}  # printing original dictionary print("The original dictionary : " +  str(test_dict))  # Initialize value  K = 2  # Using count() + values() list1=list(test_dict.values())  # Selective key values in dictionary res = list1.count(K)     # printing result  print("Frequency of K is : " + str(res)) 

Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3

Time Complexity: O(n)
Auxiliary Space : O(n)

Method #4: Using lambda functions

Python3
# Python3 code to demonstrate working of # Count keys with particular value in dictionary  # Initialize dictionary test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}  # printing original dictionary print("The original dictionary : " + str(test_dict))  # Initialize value K = 2  keys = list(test_dict.keys()) res = len(list(filter(lambda x: test_dict[x] == K, keys)))  # printing result print("Frequency of K is : " + str(res)) 

Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using collections.Counter()

Python3
# Python3 code to demonstrate working of # Count keys with particular value in dictionary # Using collections.Counter()   # Importing collections for Counter import collections   # Initialize dictionary test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}   # printing original dictionary print("The original dictionary : " + str(test_dict))   # Initialize value K = 2   # Using collections.Counter() res = collections.Counter(test_dict.values())[K]       # printing result print("Frequency of K is : " + str(res)) #This code is contributed by Edula Vinay Kumar Reddy 

Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #6: Using operator.countOf() method:

Python3
# Python3 code to demonstrate working of # Count keys with particular value in dictionary import operator as op # Initialize dictionary test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}  # printing original dictionary print("The original dictionary : " +  str(test_dict))  # Initialize value  K = 2  # Using count() + values() list1=list(test_dict.values())  # Selective key values in dictionary res = op.countOf(list1,K)     # printing result  print("Frequency of K is : " + str(res)) 

Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2} Frequency of K is : 3

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 7: Using a dictionary comprehension

Step-by-step approach:

  • Create a new dictionary using a dictionary comprehension that counts the occurrence of values in the original dictionary.
  • Create another dictionary using a dictionary comprehension that counts the occurrence of keys with a particular value in the original dictionary.
  • Access the value of the key equal to the given value K in the second dictionary to get the frequency
Python3
# Initialize dictionary test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}  # Initialize value K = 2  # Create a new dictionary with count of values as keys count_dict = {v: list(test_dict.values()).count(v) for v in set(test_dict.values())}  # Create a new dictionary with count of keys with particular value as values freq_dict = {v: sum(1 for k in test_dict.keys() if test_dict[k] == v) for v in count_dict.keys()}  # Access the frequency of K res = freq_dict[K]  # printing result print("Frequency of K is : " + str(res)) 

Output
Frequency of K is : 3

Time complexity: O(n^2)
Auxiliary space: O(n)


Next Article
Python | Count keys with particular value in dictionary

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

    Python Print Dictionary Keys and Values
    When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values.Example: Using print() MethodPythonmy_dict = {'a': 1, 'b': 2, 'c': 3} print("Keys:", l
    2 min read
    Python - Count if dictionary position equals key or value
    Given a dictionary, count instances where dictionary item position equals key or value. Valid for Py >= 3.6 [ Introduction of dictionary ordering ]. Input : test_dict = {5:3, 2:3, 10:4, 7:3, 8:1, 9:5} Output : 2 Explanation : At 3 and 5th position, values are 3 and 5. Input : test_dict = {5:3, 2:
    3 min read
    Count the Key from Nested Dictionary in Python
    In Python, counting the occurrences of keys within a nested dictionary often requires traversing through its complex structure. In this article, we will see how to count the key from the nested dictionary in Python. Count the Key from the Nested Dictionary in PythonBelow are some ways and examples b
    4 min read
    Get the number of keys with given value N in dictionary - Python
    Our task is to count how many keys have a specific value n in a given dictionary. For example, in: data = {'a': 5, 'b': 3, 'c': 5, 'd': 7, 'e': 5} and n = 5. The keys 'a', 'c', and 'e' have the value 5 so the output should be 3.Using Counter from collectionsWe count occurrences of each value using C
    2 min read
    How to Print Dictionary Keys in Python
    We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair. For example, if we have a dictionary like this: {'gfg': 1, 'is': 2, 'best': 3} then the output will be ['gfg', 'is', 'best']. Below, are the me
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences