Python – Find occurrences for each value of a particular key

PythonServer Side ProgrammingProgramming

When it is required to find the occurrences for each value of a particular key, a list comprehension and the lambda method is used.

Below is a demonstration of the same −

Example

from itertools import groupby
my_dict = [{'pyt' : 13, 'fun' : 44}, {'pyt' : 63, 'best' : 15},{'pyt' : 24, 'fun' : 34}, {'pyt' : 47, 'best' : 64} ]

print("The dictionary is :")
print(my_dict)

my_key = 'pyt'
print("The key value is :")
print(my_key)

my_result = [{keys: len(list(value))} for keys, value in groupby(my_dict, lambda index: index[my_key])]

print("The result is :")
print(my_result)

Output

The dictionary is :
[{'pyt': 13, 'fun': 44}, {'pyt': 63, 'best': 15}, {'pyt': 24, 'fun': 34}, {'pyt': 47, 'best': 64}]
The key value is :
pyt
The result is :
[{13: 1}, {63: 1}, {24: 1}, {47: 1}]

Explanation

  • The required packages are imported into the environment.

  • A list of dictionary is defined and displayed on the console.

  • The value for key is defined and displayed on the console.

  • A list comprehension is used to iterate over the list, and every element is converted to list and the ‘groupby’ method is used to group the elements of the dictionary and index of key.

  • This is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 08:55:11
Advertisements