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 - Associated Values Frequencies in Dictionary
Next article icon

Python - Associated Values Frequencies in Dictionary

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with dictionaries, we can have problem in which we need to compute the values associated to each value in dictionary in records list. This kind of problem is peculiar, but can have application in development domains. Lets discuss certain way in which this task can be performed. 

Counting  Associated Values Frequencies in Dictionary

Let us see a few methods by which we can calculate associated values frequencies in a Python Dictionary.

Using nested defaultdict() + Counter() 

The combination of defaultdict() and counter() functions can be used to solve this problem. In this, we use nested defaultdict to keep track of elements, and counting of elements is done by Counter(). 

Python3
# Python3 code to demonstrate working of  # Associated Values Frequencies in Dictionary # Using defaultdict() + Counter() from collections import defaultdict, Counter  # initializing list test_list = [{'gfg' : 1, 'is' : 3, 'best' : 4},              {'gfg' : 3, 'is' : 2, 'best' : 4},               {'gfg' : 3, 'is' : 5, 'best' : 2},              {'gfg' : 5, 'is' : 2, 'best' : 1},              {'gfg' : 2, 'is' : 4, 'best' : 3},              {'gfg' : 1, 'is' : 3, 'best' : 5},              {'gfg' : 1, 'is' : 3, 'best' : 2}]  # Associated Values Frequencies in Dictionary # Using defaultdict() + Counter() res = defaultdict(Counter) for sub in test_list:     for key, val in sub.items():         res[key][val] += 1  # printing result  print("The list after Frequencies : " + str(dict(res)))  

Output:

The list after Frequencies : {'gfg': Counter({1: 3, 3: 2, 5: 1, 2: 1}),  'is': Counter({3: 3, 2: 2, 5: 1, 4: 1}), 'best': Counter({4: 2, 2: 2, 1: 1, 3: 1, 5: 1})}

Time complexity: O(n*n), where n is the number of values in the dictionary.
Auxiliary Space: O(1), constant extra space is required

Using loops and a dictionary

In this approach, we will use nested loops to iterate through the original list and store the frequencies in a dictionary.

Python3
from collections import Counter  original_list = [{'gfg': 1, 'is': 3, 'best': 4},                   {'gfg': 3, 'is': 2, 'best': 4},                   {'gfg': 3, 'is': 5, 'best': 2},                   {'gfg': 5, 'is': 2, 'best': 1},                   {'gfg': 2, 'is': 4, 'best': 3},                   {'gfg': 1, 'is': 3, 'best': 5},                   {'gfg': 1, 'is': 3, 'best': 2}]  frequencies = {}  for item in original_list:     for key, value in item.items():         if key not in frequencies:             frequencies[key] = Counter()         frequencies[key][value] += 1  print(frequencies) 

Output:

{'gfg': Counter({1: 3, 3: 2, 5: 1, 2: 1}),  'is': Counter({3: 3, 2: 2, 5: 1, 4: 1}), 'best': Counter({4: 2, 2: 2, 1: 1, 3: 1, 5: 1})}

Time complexity: O(n^2), where n is the size of the list
Space complexity: O(n)

Using a dictionary comprehension 

This algorithm uses a dictionary comprehension to iterate over the keys in the first dictionary of test_list and create a new dictionary freq_dict where each key maps to a Counter object containing the frequency counts of the corresponding value in each dictionary in test_list. The Counter function is used to count the frequencies.

ALGORITHM:

1.Initialize an empty dictionary to store the frequencies of values for each key.
2.Use dictionary comprehension with the Counter() function to iterate over each key in the first dictionary of test_list, and count the frequency of values for that key across all the dictionaries in test_list.
3.Return the resulting dictionary of dictionaries containing the frequencies of values for each key.

Python3
from collections import Counter  test_list = [{'gfg' : 1, 'is' : 3, 'best' : 4},              {'gfg' : 3, 'is' : 2, 'best' : 4},              {'gfg' : 3, 'is' : 5, 'best' : 2},              {'gfg' : 5, 'is' : 2, 'best' : 1},              {'gfg' : 2, 'is' : 4, 'best' : 3},              {'gfg' : 1, 'is' : 3, 'best' : 5},              {'gfg' : 1, 'is' : 3, 'best' : 2}]  freq_dict = {k: Counter(d[k] for d in test_list) for k in test_list[0]} print(freq_dict) 

Output:

{'gfg': Counter({1: 3, 3: 2, 5: 1, 2: 1}),  'is': Counter({3: 3, 2: 2, 5: 1, 4: 1}), 'best': Counter({4: 2, 2: 2, 1: 1, 3: 1, 5: 1})}

Time complexity: O(nm), where n is the number of dictionaries in test_list and m is the number of keys in each dictionary.

Auxiliary Space: O(m), where m is the number of keys in each dictionary.

Using the Pandas library 

Approach:

  1. Import the Python Pandas library using the import pandas as pd statement.
  2. Define the test_list variable as a list of dictionaries, where each dictionary represents a row in a table.
  3. Convert the list of dictionaries to a pandas DataFrame using the pd.DataFrame() constructor.
  4. Define an empty dictionary freq_dict to store the frequency of each value for each key in the DataFrame.
  5. Iterate over each column (key) in the DataFrame using a for loop.
  6. For each column, use the value_counts() method to count the frequency of each value and store the resulting Series as a dictionary using the to_dict() method.
  7. Store the frequency dictionary for each key in the freq_dict dictionary.
  8. Print the freq_dict dictionary.
Python3
import pandas as pd  test_list = [{'gfg' : 1, 'is' : 3, 'best' : 4},                          {'gfg' : 3, 'is' : 2, 'best' : 4},                          {'gfg' : 3, 'is' : 5, 'best' : 2},                          {'gfg' : 5, 'is' : 2, 'best' : 1},                          {'gfg' : 2, 'is' : 4, 'best' : 3},                          {'gfg' : 1, 'is' : 3, 'best' : 5},                          {'gfg' : 1, 'is' : 3, 'best' : 2}]  df = pd.DataFrame(test_list) freq_dict = {} for k in df.columns:     freq_dict[k] = df[k].value_counts().to_dict()  print(freq_dict) 

Output:

{'gfg': {1: 3, 3: 2, 5: 1, 2: 1}, 'is': {3: 3, 2: 2, 5: 1, 4: 1}, 'best': {4: 2, 2: 2, 1: 1, 3: 1, 5: 1}}

Time complexity: O(NKV), where N is the number of dictionaries in the list, K is the average number of keys in a dictionary, and V is the average number of unique values for a key. 

Auxiliary space: O(NKV), since we are creating a DataFrame and several dictionaries to store the frequencies.


Next Article
Python - Associated Values Frequencies in Dictionary

M

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

Similar Reads

    Python - Values frequency across Dictionaries lists
    Given two list of dictionaries, compute frequency corresponding to each value in dictionary 1 to second. Input : test_list1 = [{"Gfg" : 6}, {"best" : 10}], test_list2 = [{"a" : 6}, {"b" : 10}, {"d" : 6}}] Output : {'Gfg': 2, 'best': 1} Explanation : 6 has 2 occurrence in 2nd list, 10 has 1. Input :
    6 min read
    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 Program to calculate Dictionaries frequencies
    Given a list of dictionaries, the task here is to write a python program to extract dictionary frequencies of each dictionary. Input : test_list = [{'gfg' : 1, 'is' : 4, 'best' : 9}, {'gfg' : 6, 'is' : 3, 'best' : 8}, {'gfg' : 1, 'is' : 4, 'best' : 9}, {'gfg' : 1, 'is' : 1, 'best' : 9}, {'gfg' : 6,
    6 min read
    Counting the Frequencies in a List Using Dictionary in Python
    Counting the frequencies of items in a list using a dictionary in Python can be done in several ways. For beginners, manually using a basic dictionary is a good starting point. Using Manual MethodIt uses a basic dictionary to store the counts, and the logic checks whether the item is already in the
    3 min read
    Python - Convert Frequency dictionary to list
    When we convert a frequency dictionary to a list, we are transforming the dictionary into a list of key-value or just the keys/values, depending on needs. We can convert a frequency dictionary to a list using methods such as list comprehension, loops, extend() method and itertools.chain() function.F
    3 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