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:
Counting number of unique values in a Python list
Next article icon

Python - Unique values count of each Key

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

Given a Dictionaries list, the task is to write a Python program to count the unique values of each key.

Example:

Input : test_list = [{"gfg" : 1, "is" : 3, "best": 2}, {"gfg" : 1, "is" : 3, "best" : 6},                      {"gfg" : 7, "is" : 3, "best" : 10}] Output : {'gfg': 2, 'is': 1, 'best': 3} Explanation : gfg has 1 and 7 as unique elements, hence 2.
Input : test_list = [{"gfg" : 1, "is" : 3, "best": 2}, {"gfg" : 1, "is" : 3, "best" : 6},                      {"gfg" : 1, "is" : 3, "best" : 10}] Output : {'gfg': 1, 'is': 1, 'best': 3} Explanation : gfg has only 1 as unique element, hence 1.

Method #1 : Using len() + set() + loop

In this, unique values is extracted using set(), len() is used to get its count, and then the result is mapped to each key extracted using keys(). Iterating over keys occurs in a loop.

Python3
# Python3 code to demonstrate working of # Unique values count of each Key # Using len() + set()  # initializing lists test_list = [{"gfg": 1, "is": 3, "best": 2}, {     "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # printing original list print("The original list is : " + str(test_list))  res = dict() for key in test_list[0].keys():      # mapping unique values.     res[key] = len(set([sub[key] for sub in test_list]))  # printing result print("Unique count of keys : " + str(res)) 

Output
The original list is : [{'gfg': 1, 'is': 3, 'best': 2}, {'gfg': 1, 'is': 3, 'best': 6}, {'gfg': 7, 'is': 3, 'best': 10}] Unique count of keys : {'gfg': 2, 'is': 1, 'best': 3} 

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

Method #2 : Using dictionary comprehension + len() + set()

Similar to the above method, the difference is dictionary comprehension is used as one-liner alternative for shorthand.

Python3
# Python3 code to demonstrate working of # Unique values count of each Key # Using len() + set() + dictionary comprehension  # Initializing lists test_list = [{"gfg": 1, "is": 3, "best": 2}, {     "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # Printing original list print("The original list is : " + str(test_list))  # Dictionary comprehension for compact solution res = {key: len(set([sub[key] for sub in test_list]))        for key in test_list[0].keys()}  # Printing uunique counts of kets as result print("Unique count of keys : " + str(res)) 

Output
The original list is : [{'gfg': 1, 'is': 3, 'best': 2}, {'gfg': 1, 'is': 3, 'best': 6}, {'gfg': 7, 'is': 3, 'best': 10}] Unique count of keys : {'gfg': 2, 'is': 1, 'best': 3} 

Time Complexity: O(n) where n is the number of elements in the list “test_list”. The dictionary comprehension + len() + set() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n), new list of size O(n) is created where n is the number of elements in the list 

Method #3:Using Counter() method

Python3
# Python3 code to demonstrate working of # Unique values count of each Key from collections import Counter  # initializing lists test_list = [{"gfg": 1, "is": 3, "best": 2}, {     "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # printing original list print("The original list is : " + str(test_list))  res = dict() for key in test_list[0].keys():      # mapping unique values.     res[key] = len(Counter([sub[key] for sub in test_list]))  # printing result print("Unique count of keys : " + str(res)) 

Output
The original list is : [{'gfg': 1, 'is': 3, 'best': 2}, {'gfg': 1, 'is': 3, 'best': 6}, {'gfg': 7, 'is': 3, 'best': 10}] Unique count of keys : {'gfg': 2, 'is': 1, 'best': 3}

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

Method #4: Using for loop

We can use for loop for unique value count in each key. We can traverse each element in the dictionary and check

Here is the step-by-step algorithm for the implementation of the code:

  1. Initialize the list of dictionaries test_list.
  2. Initialize an empty dictionary res to store the result.
  3. Iterate through the keys of the first dictionary in test_list.
  4. For each key, create a temporary list temp_list that contains the values of that key from all the dictionaries in test_list.
  5. Create a set temp_set from the temp_list to get the unique values.
  6. Add the length of temp_set as the value for the corresponding key in the res dictionary.
  7. Print the resulting res dictionary.
Python
# initializing lists test_list = [{"gfg": 1, "is": 3, "best": 2}, {    "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # printing original list print("The original list is : " + str(test_list))  res = dict() for key in test_list[0].keys():     temp_list = [sub[key] for sub in test_list]     temp_set = set()     for i in temp_list:         temp_set.add(i)     res[key] = len(temp_set)  # printing result print("Unique count of keys : " + str(res)) #This code is contributed by Vinay Pinjala. 

Output
The original list is : [{'is': 3, 'gfg': 1, 'best': 2}, {'is': 3, 'gfg': 1, 'best': 6}, {'is': 3, 'gfg': 7, 'best': 10}] Unique count of keys : {'is': 1, 'gfg': 2, 'best': 3}

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

Method #5: Using numpy

Algorithm:

  1. Iterate through each key in the first dictionary in the list of dictionaries.
  2. For each key, create a numpy array with the values of the corresponding key in each dictionary.
  3. Use the numpy.unique() function to get the unique values of the array.
  4. Get the length of the unique values array and store it as the value for the current key in the result dictionary.
  5. Return the result dictionary.
Python3
import numpy as np  # input list  test_list = [{"gfg": 1, "is": 3, "best": 2},              {"gfg": 1, "is": 3, "best": 6},              {"gfg": 7, "is": 3, "best": 10}]  result = {}  # printing original list print("The original list is : " + str(test_list))  # Looking for key in our list for key in test_list[0]:     values = np.array([d[key] for d in test_list])     result[key] = len(np.unique(values))   # Printing result print("Unique count of keys : " + str(result))  # This code is contributed by Rayudu 

Output
The original list is : [{'is': 3, 'gfg': 1, 'best': 2}, {'is': 3, 'gfg': 1, 'best': 6}, {'is': 3, 'gfg': 7, 'best': 10}] Unique count of keys : {'is': 1, 'gfg': 2, 'best': 3}

Time complexity: O(K)
The algorithm iterates through each key in the first dictionary in the list once, which takes O(k) time, where k is the number of keys in the dictionary.
For each key, the algorithm creates a numpy array with the values of the corresponding key in each dictionary. This takes O(n) time, where n is the number of dictionaries in the list.
The numpy.unique() function takes O(m log m) time, where m is the number of unique values in the array.
Getting the length of the unique values array takes O(1) time.
Therefore, the overall time complexity of the algorithm is O(kn(m log m)).

Auxiliary Space: O(nk + m)
The algorithm creates a numpy array for each key, which takes O(nk) space, where n is the number of dictionaries in the list and k is the number of keys in each dictionary. The numpy.unique() function creates a copy of the array, which takes O(m) space.
The result dictionary takes O(k) space to store the counts of unique values for each key.
Therefore, the overall space complexity of the algorithm is O(nk + m + k), which simplifies to O(nk + m).

Method 6:  use the pandas library

Python3
import pandas as pd  # initializing lists test_list = [{"gfg": 1, "is": 3, "best": 2}, {"gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # printing original list print("The original list is : " + str(test_list))  # create DataFrame df = pd.DataFrame(test_list)  # get unique count of keys res = df.nunique().to_dict()  # printing result print("Unique count of keys : " + str(res)) 

Output
The original list is : [{'is': 3, 'gfg': 1, 'best': 2}, {'is': 3, 'gfg': 1, 'best': 6}, {'is': 3, 'gfg': 7, 'best': 10}] Unique count of keys : {'is': 1, 'gfg': 2, 'best': 3}

Time complexity: O(n), where n is the total number of elements in the list of dictionaries.
Auxiliary space: O(n), where n is the total number of elements in the list of dictionaries, due to the creation of the pandas DataFrame.


Next Article
Counting number of unique values in a Python list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

  • Python - Unique Values of Key in Dictionary
    We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name" Then, the unique value
    4 min read
  • Python - Extract Unique value key pairs
    Sometimes, while working on Python dictionaries, we can have a problem in which we need to perform the extraction of selected pairs of keys from dictionary list, that too unique. This kind of problem can have application in many domains including day-day programming. Let's discuss certain ways in wh
    5 min read
  • Counting number of unique values in a Python list
    Counting the number of unique values in a Python list involves determining how many distinct elements are present disregarding duplicates. Using a SetUsing a set to count the number of unique values in a Python list leverages the property of sets where each element is stored only once. [GFGTABS] Pyt
    2 min read
  • Python | Unique values in Matrix
    Sometimes we need to find the unique values in a list, which is comparatively easy and has been discussed earlier. But we can also get a matrix as input i.e a list of lists, and finding unique in them are discussed in this article. Let's see certain ways in which this can be achieved. Method #1: Usi
    9 min read
  • Python - Values frequencies of key
    Sometimes, while working with Python dictionary lists, one can have a problem in which we require to find the frequency of all the values occurring in a specific key in dictionary list. This can have application across many domains including web development. Let's discuss certain ways in which this
    7 min read
  • Key with Maximum Unique Values - Python
    The task involves finding the key whose list contains the most unique values in a dictionary. Each list is converted to a set to remove duplicates and the key with the longest set is identified. For example, in d = {"A": [1, 2, 2], "B": [3, 4, 5, 3], "C": [6, 7, 7, 8]}, key "C" has the most unique v
    3 min read
  • Python program to unique keys count for Value in Tuple List
    Given dual tuples, get a count of unique keys for each value present in the tuple. Input : test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)] Output : {4: 4, 2: 3, 1: 2} Explanation : 3, 2, 8 and 10 are keys for value 4. Input : test_list = [(3, 4), (1, 2), (8, 1),
    6 min read
  • Set from Dictionary Values - Python
    The task is to extract unique values from a dictionary and convert them into a set. In Python, sets are unordered collections that automatically eliminate duplicates. The goal is to extract all the values from the dictionary and store them in a set. For example, given a dictionary like d = {'A': 4,
    3 min read
  • Assign Ids to Each Unique Value in a List - Python
    The task of assigning unique IDs to each value in a list involves iterating over the elements and assigning a unique identifier to each distinct value. Since lists in Python are mutable, the goal is to efficiently assign an ID to each unique element while ensuring that repeated elements receive the
    3 min read
  • Python Tuple count() Method
    In this article, we will learn about the count() method used for tuples in Python. The count() method of a Tuple returns the number of times the given element appears in the tuple. Example [GFGTABS] Python3 tuple = (1, 2, 3, 1, 2, 3, 1, 2, 3) print(tuple.count(3)) [/GFGTABS] Output : 3Python Tuple c
    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