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 - Find occurrences for each value of a particular key
Next article icon

Python - Find occurrences for each value of a particular key

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

Given a List of dictionaries, for a particular key, find the number of occurrences for each value of that key.

Input : test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5}, 
{'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ], K = 'gfg' 
Output : [{3: 2}, {4: 1}, {7: 1}] 
Explanation : gfg has 2 occurrences of 3 as values.


Input : test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5}, 
{'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ], K = 'best' 
Output : [{4: 3}, {5: 1}] 
Explanation : best has 3 occurrences of 4 as values.

Method #1 : Using groupby() + dictionary comprehension

In this, we perform grouping of key's values using groupby() and values frequency is assembled and extracted using dictionary comprehension and len().

Python3
# Python3 code to demonstrate working of  # Values Frequency grouping of K in dictionaries # Using groupby() + dictionary comprehension from itertools import groupby  # initializing list test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5},               {'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ]  # printing original list print("The original list is : " + str(test_list))  # initializing K  K = 'gfg'  # groupby() used to group values and len() to compute Frequency res = [{key: len(list(val))} for key, val in groupby(test_list, lambda sub: sub[K])]  # printing result  print("The Values Frequency : " + str(res)) 

Output:

The original list is : [{'gfg': 3, 'best': 4}, {'gfg': 3, 'best': 5}, {'gfg': 4, 'best': 4}, {'gfg': 7, 'best': 4}] The Values Frequency : [{3: 2}, {4: 1}, {7: 1}]

Time Complexity: O(n) where n is the number of elements in the list “test_list”.  groupby() + dictionary comprehension performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list 

Method #2 : Using Counter()

In this, the task of performing frequency check is done using Counter(). Returns result in single dictionary.

Python3
# Python3 code to demonstrate working of  # Values Frequency grouping of K in dictionaries # Using Counter() from collections import Counter  # initializing list test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5},               {'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ]  # printing original list print("The original list is : " + str(test_list))  # initializing K  K = 'gfg'  # groupby() used to group values and len() to compute Frequency res = dict(Counter(sub[K] for sub in test_list))  # printing result  print("The Values Frequency : " + str(res)) 

 Output:

The original list is : [{'gfg': 3, 'best': 4}, {'gfg': 3, 'best': 5}, {'gfg': 4, 'best': 4}, {'gfg': 7, 'best': 4}] The Values Frequency : [{3: 2}, {4: 1}, {7: 1}]

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

Python3
# Python3 code to demonstrate working of # Values Frequency grouping of K in dictionaries  # initializing list test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5},             {'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ]  # printing original list print("The original list is : " + str(test_list))  # initializing K K = 'gfg' x=[] for i in test_list:     if K in i.keys():         x.append(i[K]) p=list(set(x)) nl=[] for i in p:     d={}     d[i]=x.count(i)     nl.append(d)  # printing result print("The Values Frequency : " + str(nl)) 

Output
The original list is : [{'gfg': 3, 'best': 4}, {'gfg': 3, 'best': 5}, {'gfg': 4, 'best': 4}, {'gfg': 7, 'best': 4}] The Values Frequency : [{3: 2}, {4: 1}, {7: 1}]

Method#4:Using defaultdict() and loop

Algorithm:

  1. Create an empty dictionary and set the default value to 0.
  2. Iterate over the list of dictionaries.
  3. For each dictionary, get the value of key K.
  4. Use this value to update the count in the dictionary created in step 1.
  5. Return the resulting dictionary.
Python3
from collections import defaultdict  # initializing list test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5},              {'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ]  # initializing K K = 'gfg'  # using loop and defaultdict to group values and compute frequency freq_dict = defaultdict(int) for item in test_list:     freq_dict[item[K]] += 1  # formatting the result as a list of dictionaries res = [{key: val} for key, val in freq_dict.items()]  # printing result  print("The Values Frequency : " + str(res))  #This code is contributed by Vinay Pinjala. 

Output
The Values Frequency : [{3: 2}, {4: 1}, {7: 1}]

Time Complexity: O(n), where n is the number of dictionaries in the list. This is because we need to iterate over each dictionary once.

Space Complexity: O(k), where k is the number of unique values for key K. This is because we are storing the count for each unique value in the resulting dictionary.

Method #5: Using pandas
Step-by-step approach:

Import pandas library.
Convert the list of dictionaries to a pandas DataFrame using the pd.DataFrame() function.
Use the value_counts() method on the 'gfg' column of the DataFrame to get the frequency of each unique value.
Convert the resulting pandas Series object to a dictionary using the to_dict() method.
Format the dictionary as a list of dictionaries using a list comprehension.
Print the resulting list of dictionaries.

Python3
import pandas as pd  # initializing list test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5},              {'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ]  # initializing K K = 'gfg'  # convert list of dictionaries to pandas DataFrame df = pd.DataFrame(test_list)  # get frequency of each unique value in 'gfg' column freq_dict = df[K].value_counts().to_dict()  # format the result as a list of dictionaries res = [{key: val} for key, val in freq_dict.items()]  # print the result print("The Values Frequency : " + str(res)) 
OUTPUT : The Values Frequency : [{3: 2}, {4: 1}, {7: 1}]

Time complexity: O(n log n), where n is the number of items in the input list. 

Auxiliary space: O(n), where n is the number of items in the input list.


Next Article
Python - Find occurrences for each value of a particular key

M

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

Similar Reads

    Python program to Count the Number of occurrences of a key-value pair in a text file
    Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file with PythonProgram to Count the occurrences of a key-value pairNaive Approach to Count the Occurrences of a key-value PairUsing Python built-in collections.CounterUsing regular exp
    3 min read
    Element Occurrence in Dictionary of List Values - Python
    We are having a dictionary of list we need to find occurrence of all elements. For example, d = {'a': [1, 2, 3, 1], 'b': [3, 4, 1], 'c': [1, 5, 6]} we need to count the occurrence of all elements in dictionary list so that resultant output should be {'a': 2, 'b': 1, 'c': 1}.Using a Dictionary Compre
    3 min read
    Python | Count keys with particular value in dictionary
    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 o
    5 min read
    Python - Count occurrences of each word in given text file
    Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the w
    4 min read
    Python program to find occurrence to each character in given string
    Given a string, the task is to write a program in Python that prints the number of occurrences of each character in a string. There are multiple ways in Python, we can do this task. Let's discuss a few of them. Method #1: Using set() + count() Iterate over the set converted string and get the count
    5 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