Python – Unique values count of each Key

• Last Updated : 24 Jan, 2021

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 occur in loop.

Python3

 # Python3 code to demonstrate working of# Unique values count of each Key# Using len() + set()  # initializing liststest_list = [{"gfg": 1, "is": 3, "best": 2}, {    "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # printing original listprint("The original list is : " + str(test_list))  res = dict()for key in test_list.keys():      # mapping unique values.    res[key] = len(set([sub[key] for sub in test_list]))  # printing resultprint("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}

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

Similar to above method, difference being 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 liststest_list = [{"gfg": 1, "is": 3, "best": 2}, {    "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}]  # printing original listprint("The original list is : " + str(test_list))  # dictionary comprehension for compact solutionres = {key: len(set([sub[key] for sub in test_list]))       for key in test_list.keys()}  # printing resultprint("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}

My Personal Notes arrow_drop_up