Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Dictionaries in Python
Next article icon

Python – Frequencies of Values in a Dictionary

Last Updated : 25 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_dict = {‘ide’ : 3, ‘Gfg’ : 3, ‘code’ : 2} 
Output : {3: 2, 2: 1} 

Input : test_dict = {10 : 1, 20 : 2, 30 : 1, 40 : 2 } 
Output : {1 : 2, 2 : 2}

Method #1 : Using defaultdict() + loop The combination of above functions can be used to solve this problem. In this, we use defaultdict() to initialize the counter dictionary with integers and increment counter in brute force manner using loop. 

Python3




# Python3 code to demonstrate working of
# Dictionary Values Frequency
# Using defaultdict() + loop
from collections import defaultdict
 
# initializing dictionary
test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Dictionary Values Frequency
# Using defaultdict() + loop
res = defaultdict(int)
for key, val in test_dict.items():
    res[val] += 1
     
# printing result
print("The frequency dictionary : " + str(dict(res)))
 
 
Output:
The original dictionary : {'Gfg': 3, 'code': 2, 'ide': 3} The frequency dictionary : {2: 1, 3: 2}

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #2 : Using Counter() + values() The combination of above functions can be used to solve this problem. In this, we perform the task of extraction of values using values() and frequency counter using Counter(). 

Python3




# Python3 code to demonstrate working of
# Dictionary Values Frequency
# Using Counter() + values()
from collections import Counter
 
# initializing dictionary
test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Dictionary Values Frequency
# Using defaultdict() + loop
res = Counter(test_dict.values())
     
# printing result
print("The frequency dictionary : " + str(dict(res)))
 
 
Output:
The original dictionary : {'code': 2, 'Gfg': 3, 'ide': 3} The frequency dictionary : {2: 1, 3: 2}

Method #3 : Using values(),count(),list(),set() methods

Approach

  1. Create an empty dictionary res, store the values of dictionary in a list x(list(),values())
  2. Store the unique values of a list x in list y(using list(),set())
  3. Initiate a for loop to traverse unique values list y
  4. Inside for loop with unique value as key and count of unique value in list y as value(using count())
  5. Display output dictionary res

Python3




# Python3 code to demonstrate working of
# Dictionary Values Frequency
 
# initializing dictionary
test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Dictionary Values Frequency
 
res=dict()
x=list(test_dict.values())   
y=list(set(x))
for i in y:
    res[i]=x.count(i)
# printing result
print("The frequency dictionary : " + str(res))
 
 
Output
The original dictionary : {'ide': 3, 'Gfg': 3, 'code': 2} The frequency dictionary : {2: 1, 3: 2}

Time Complexity: O(N), where N is the length of dictionary values list
Auxiliary Space: O(N)

Method #4: Using values(),operator.countOf(),list(),set() methods

Step-by-step approach:

  1. Create an empty dictionary res, store the values of dictionary in a list x(list(),values())
  2. Store the unique values of a list x in list y(using list(),set())
  3. Initiate a for loop to traverse unique values list y
  4. Inside for loop with unique value as key and count of unique value in list y as value(using operator.countOf())
  5. Display output dictionary res

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Dictionary Values Frequency
 
# initializing dictionary
test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Dictionary Values Frequency
 
res=dict()
x=list(test_dict.values())   
y=list(set(x))
import operator
for i in y:
    res[i]=operator.countOf(x,i)
# printing result
print("The frequency dictionary : " + str(res))
 
 
Output
The original dictionary : {'ide': 3, 'Gfg': 3, 'code': 2} The frequency dictionary : {2: 1, 3: 2}

Time Complexity: O(N), where N is the length of dictionary values list
Auxiliary Space: O(N)



Next Article
Dictionaries in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

  • Get Key from Value in Dictionary - Python
    The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
    6 min read
  • Python dictionary values()
    values() method in Python is used to obtain a view object that contains all the values in a dictionary. This view object is dynamic, meaning it updates automatically if the dictionary is modified. If we use the type() method on the return value, we get "dict_values object". It must be cast to obtain
    2 min read
  • Counting Frequency of Values by Date in Pandas
    Counting the frequency of values by date is a common task in time-series analysis, where we need to analyze how often certain events occur within specific time frames. Understanding these frequencies can provide valuable insights if we analyze sales data, website traffic, or any other date-related d
    3 min read
  • Dictionaries in Python
    A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
    5 min read
  • How to Add Same Key Value in Dictionary Python
    Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python. Adding
    2 min read
  • Find Frequency of Characters in Python
    In this article, we will explore various methods to count the frequency of characters in a given string. One simple method to count frequency of each character is by using a dictionary. Using DictionaryThe idea is to traverse through each character in the string and keep a count of how many times it
    2 min read
  • Python | Count number of items in a dictionary value that is a list
    In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a ke
    5 min read
  • Python Dictionary Exercise
    Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
    3 min read
  • Find frequency of each word in a string in Python
    Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi A
    7 min read
  • Python dictionary, set and counter to check if frequencies can become same
    Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make th
    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