Python – Unique values count of each Key
Last Updated :
27 Apr, 2023
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
test_list = [{ "gfg" : 1 , "is" : 3 , "best" : 2 }, {
"gfg" : 1 , "is" : 3 , "best" : 6 }, { "gfg" : 7 , "is" : 3 , "best" : 10 }]
print ( "The original list is : " + str (test_list))
res = dict ()
for key in test_list[ 0 ].keys():
res[key] = len ( set ([sub[key] for sub in test_list]))
print ( "Unique count of keys : " + str (res))
|
OutputThe 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
test_list = [{ "gfg" : 1 , "is" : 3 , "best" : 2 }, {
"gfg" : 1 , "is" : 3 , "best" : 6 }, { "gfg" : 7 , "is" : 3 , "best" : 10 }]
print ( "The original list is : " + str (test_list))
res = {key: len ( set ([sub[key] for sub in test_list]))
for key in test_list[ 0 ].keys()}
print ( "Unique count of keys : " + str (res))
|
OutputThe 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
from collections import Counter
test_list = [{ "gfg" : 1 , "is" : 3 , "best" : 2 }, {
"gfg" : 1 , "is" : 3 , "best" : 6 }, { "gfg" : 7 , "is" : 3 , "best" : 10 }]
print ( "The original list is : " + str (test_list))
res = dict ()
for key in test_list[ 0 ].keys():
res[key] = len (Counter([sub[key] for sub in test_list]))
print ( "Unique count of keys : " + str (res))
|
OutputThe 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:
- Initialize the list of dictionaries test_list.
- Initialize an empty dictionary res to store the result.
- Iterate through the keys of the first dictionary in test_list.
- For each key, create a temporary list temp_list that contains the values of that key from all the dictionaries in test_list.
- Create a set temp_set from the temp_list to get the unique values.
- Add the length of temp_set as the value for the corresponding key in the res dictionary.
- Print the resulting res dictionary.
Python
test_list = [{ "gfg" : 1 , "is" : 3 , "best" : 2 }, { "gfg" : 1 , "is" : 3 , "best" : 6 }, { "gfg" : 7 , "is" : 3 , "best" : 10 }]
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)
print ( "Unique count of keys : " + str (res))
|
OutputThe 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:
- Iterate through each key in the first dictionary in the list of dictionaries.
- For each key, create a numpy array with the values of the corresponding key in each dictionary.
- Use the numpy.unique() function to get the unique values of the array.
- Get the length of the unique values array and store it as the value for the current key in the result dictionary.
- Return the result dictionary.
Python3
import numpy as np
test_list = [{ "gfg" : 1 , "is" : 3 , "best" : 2 },
{ "gfg" : 1 , "is" : 3 , "best" : 6 },
{ "gfg" : 7 , "is" : 3 , "best" : 10 }]
result = {}
print ( "The original list is : " + str (test_list))
for key in test_list[ 0 ]:
values = np.array([d[key] for d in test_list])
result[key] = len (np.unique(values))
print ( "Unique count of keys : " + str (result))
|
OutputThe 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
test_list = [{ "gfg" : 1 , "is" : 3 , "best" : 2 }, { "gfg" : 1 , "is" : 3 , "best" : 6 }, { "gfg" : 7 , "is" : 3 , "best" : 10 }]
print ( "The original list is : " + str (test_list))
df = pd.DataFrame(test_list)
res = df.nunique().to_dict()
print ( "Unique count of keys : " + str (res))
|
OutputThe 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.
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