Python Program to calculate Dictionaries frequencies
Last Updated :
02 May, 2023
Given a list of dictionaries, the task here is to write a python program to extract dictionary frequencies of each dictionary.
Input : test_list = [{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 9},
{‘gfg’ : 6, ‘is’ : 3, ‘best’ : 8},
{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 9},
{‘gfg’ : 1, ‘is’ : 1, ‘best’ : 9},
{‘gfg’ : 6, ‘is’ : 3, ‘best’ : 8}]
Output : [({‘gfg’: 1, ‘is’: 4, ‘best’: 9}, 2), ({‘gfg’: 6, ‘is’: 3, ‘best’: 8}, 2), ({‘gfg’: 1, ‘is’: 1, ‘best’: 9}, 1)]
Explanation : Dictionaries with their frequency appended as result in list.
Input : test_list = [{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 9},
{‘gfg’ : 6, ‘is’ : 3, ‘best’ : 8},
{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 9},
{‘gfg’ : 1, ‘is’ : 1, ‘best’ : 9}]
Output : [({‘gfg’: 1, ‘is’: 4, ‘best’: 9}, 2), ({‘gfg’: 6, ‘is’: 3, ‘best’: 8}, 1), ({‘gfg’: 1, ‘is’: 1, ‘best’: 9}, 1)]
Explanation : Dictionaries with their frequency appended as result in list.
Method 1 : Using index() and loop
In this, each dictionary is iterated and index() is used to get the index of dictionary mapped with its increasing frequencies, and increment counter in case of repeated dictionary.
Example:
Python3
test_list = [{ 'gfg' : 1 , 'is' : 4 , 'best' : 9 },
{ 'gfg' : 6 , 'is' : 3 , 'best' : 8 },
{ 'gfg' : 1 , 'is' : 4 , 'best' : 9 },
{ 'gfg' : 1 , 'is' : 1 , 'best' : 9 },
{ 'gfg' : 6 , 'is' : 3 , 'best' : 8 }]
print ( "The original list is : " + str (test_list))
res = []
for sub in test_list:
flag = 0
for ele in res:
if sub = = ele[ 0 ]:
res[res.index(ele)] = (sub, ele[ 1 ] + 1 )
flag = 1
if not flag:
res.append((sub, 1 ))
print ( "Dictionaries frequencies : " + str (res))
|
Output
The original list is : [{'gfg': 1, 'is': 4, 'best': 9}, {'gfg': 6, 'is': 3, 'best': 8}, {'gfg': 1, 'is': 4, 'best': 9}, {'gfg': 1, 'is': 1, 'best': 9}, {'gfg': 6, 'is': 3, 'best': 8}]
Dictionaries frequencies : [({'gfg': 1, 'is': 4, 'best': 9}, 2), ({'gfg': 6, 'is': 3, 'best': 8}, 2), ({'gfg': 1, 'is': 1, 'best': 9}, 1)]
Method 2 : Using Counter() and sorted()
In this, dictionary elements are converted to tuple pairs and then Counter is used to get frequency of each. At last step, each dictionary is reconverted to its original form.
Example:
Python3
from collections import Counter
test_list = [{ 'gfg' : 1 , 'is' : 4 , 'best' : 9 },
{ 'gfg' : 6 , 'is' : 3 , 'best' : 8 },
{ 'gfg' : 1 , 'is' : 4 , 'best' : 9 },
{ 'gfg' : 1 , 'is' : 1 , 'best' : 9 },
{ 'gfg' : 6 , 'is' : 3 , 'best' : 8 }]
print ( "The original list is : " + str (test_list))
temp = Counter( tuple ( sorted (sub.items())) for sub in test_list)
res = [( dict ([ tuple (ele) for ele in sub]), temp[sub]) for sub in temp]
print ( "Dictionaries frequencies : " + str (res))
|
Output
The original list is : [{'gfg': 1, 'is': 4, 'best': 9}, {'gfg': 6, 'is': 3, 'best': 8}, {'gfg': 1, 'is': 4, 'best': 9}, {'gfg': 1, 'is': 1, 'best': 9}, {'gfg': 6, 'is': 3, 'best': 8}]
Dictionaries frequencies : [({'best': 9, 'gfg': 1, 'is': 4}, 2), ({'best': 8, 'gfg': 6, 'is': 3}, 2), ({'best': 9, 'gfg': 1, 'is': 1}, 1)]
Method 3 : Using lambda+ list of dictionary
Approach
we will iterate through the given list of dictionaries and use a dictionary to keep track of the frequency of each dictionary. Finally, we will return the list of dictionaries along with their frequency in descending order of frequency.
Algorithm
1. Create an empty dictionary freq_dict to store the frequency of each dictionary.
2. Iterate through the given list of dictionaries.
3. For each dictionary, check if it is present in freq_dict. If it is not present, add it with a frequency of 1. If it is already present, increment its frequency.
4. Create a list of tuples from freq_dict, where each tuple contains the dictionary and its frequency.
5. Sort the list of tuples in descending order of frequency.
6. Return the sorted list of tuples.
Python3
def freq_dict_1(test_list):
freq_dict = {}
for d in test_list:
if str (d) not in freq_dict:
freq_dict[ str (d)] = 1
else :
freq_dict[ str (d)] + = 1
freq_list = [( eval (k), v) for k, v in freq_dict.items()]
freq_list.sort(key = lambda x: x[ 1 ], reverse = True )
return freq_list
test_list = [{ 'gfg' : 1 , 'is' : 4 , 'best' : 9 },
{ 'gfg' : 6 , 'is' : 3 , 'best' : 8 },
{ 'gfg' : 1 , 'is' : 4 , 'best' : 9 },
{ 'gfg' : 1 , 'is' : 1 , 'best' : 9 },
{ 'gfg' : 6 , 'is' : 3 , 'best' : 8 }]
print (freq_dict_1(test_list))
|
Output
[({'gfg': 1, 'is': 4, 'best': 9}, 2), ({'gfg': 6, 'is': 3, 'best': 8}, 2), ({'gfg': 1, 'is': 1, 'best': 9}, 1)]
Time Complexity: O(n log n), where n is the length of the given list of dictionaries. The sort() function has a time complexity of O(n log n).
Auxiliary Space: O(n), where n is the length of the given list of dictionaries. The freq_dict dictionary will have at most n entries.
Method 4: Using defaultdict and list comprehension
The defaultdict is a subclass of the dict class that provides a default value for a nonexistent key. Here, we can use it to initialize the frequency of each dictionary to zero, and then increment it as we encounter it in the list.
Step-by-step approach:
- Import the defaultdict from the collections module.
Define a function freq_dict_2 that takes a list of dictionaries as input.
- Initialize a defaultdict of integers, called freq_dict.
- Loop through each dictionary in the input list.
- Convert the dictionary to a frozenset, so it can be used as a key in the defaultdict.
- Increment the frequency of the frozenset key in the defaultdict by 1.
- Create a list of tuples using a list comprehension, where each tuple contains the dictionary (converted from the frozenset), and its frequency.
- Sort the list of tuples by frequency in descending order.
- Return the sorted list of tuples.
Python3
from collections import defaultdict
def freq_dict_2(test_list):
freq_dict = defaultdict( int )
for d in test_list:
freq_dict[ frozenset (d.items())] + = 1
freq_list = [( dict (k), v) for k, v in freq_dict.items()]
freq_list.sort(key = lambda x: x[ 1 ], reverse = True )
return freq_list
test_list = [{ 'gfg' : 1 , 'is' : 4 , 'best' : 9 },
{ 'gfg' : 6 , 'is' : 3 , 'best' : 8 },
{ 'gfg' : 1 , 'is' : 4 , 'best' : 9 },
{ 'gfg' : 1 , 'is' : 1 , 'best' : 9 },
{ 'gfg' : 6 , 'is' : 3 , 'best' : 8 }]
print (freq_dict_2(test_list))
|
Output
[({'is': 4, 'gfg': 1, 'best': 9}, 2), ({'gfg': 6, 'is': 3, 'best': 8}, 2), ({'is': 1, 'gfg': 1, 'best': 9}, 1)]
Time Complexity: O(nlogn), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the input list.
Similar Reads
Python program to equal character frequencies
Given a String, ensure it has equal character frequencies, if not, equate by adding required characters. Input : test_str = 'geeksforgeeks' Output : geeksforgeeksggkkssfffooorrr Explanation : Maximum characters are 4 of 'e'. Other character are appended of frequency 4 - (count of chars). Input : tes
2 min read
Python - Associated Values Frequencies in Dictionary
Sometimes, while working with dictionaries, we can have problem in which we need to compute the values associated to each value in dictionary in records list. This kind of problem is peculiar, but can have application in development domains. Lets discuss certain way in which this task can be perform
5 min read
Python program to count Even and Odd numbers in a Dictionary
Given a python dictionary, the task is to count even and odd numbers present in the dictionary. Examples: Input : {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e' : 5}Output : Even = 2, odd = 3Input : {'x': 4, 'y':9, 'z':16}Output : Even = 2, odd = 1 Approach using values() Function: Traverse the dictionary and
3 min read
Python program to multiply all the items in a dictionary
Python program to illustrate multiplying all the items in a dictionary could be done by creating a dictionary that will store all the key-value pairs, multiplying the value of all the keys, and storing it in a variable. Example: Input: dict = {'value1':5, 'value2':4, 'value3':3, 'value4':2, 'value5'
2 min read
Python - Values frequency across Dictionaries lists
Given two list of dictionaries, compute frequency corresponding to each value in dictionary 1 to second. Input : test_list1 = [{"Gfg" : 6}, {"best" : 10}], test_list2 = [{"a" : 6}, {"b" : 10}, {"d" : 6}}] Output : {'Gfg': 2, 'best': 1} Explanation : 6 has 2 occurrence in 2nd list, 10 has 1. Input :
6 min read
Python program to divide dictionary and its keys into K equal dictionaries
Given a dictionary, divide it into an equal dictionary list of size k, by dividing each key's value. Input : test_dict = {"Gfg" : 9, "is" : 6, "best" : 12} , K = 3 Output : [{'Gfg': 3.0, 'is': 2.0, 'best': 4.0}, {'Gfg': 3.0, 'is': 2.0, 'best': 4.0}, {'Gfg': 3.0, 'is': 2.0, 'best': 4.0}] Explanation
3 min read
Python - Frequency Grouping Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the grouping of dictionary data, in a way in which we need to group all the similar dictionaries key with its frequency. This kind of problem has its application in web development domain. Let's disc
4 min read
How to Create a Python Dictionary from Text File?
The task of creating a Python dictionary from a text file involves reading its contents, extracting key-value pairs and storing them in a dictionary. Text files typically use delimiters like ':' or ',' to separate keys and values. By processing each line, splitting at the delimiter and removing extr
3 min read
Calculating the Product of List Lengths in a Dictionary - Python
The task of calculating the product of the lengths of lists in a dictionary involves iterating over the dictionaryâs values, which are lists and determining the length of each list. These lengths are then multiplied together to get a single result. For example, if d = {'A': [1, 2, 3], 'B': [4, 5], '
3 min read
Counting the Frequencies in a List Using Dictionary in Python
Counting the frequencies of items in a list using a dictionary in Python can be done in several ways. For beginners, manually using a basic dictionary is a good starting point. Using Manual MethodIt uses a basic dictionary to store the counts, and the logic checks whether the item is already in the
3 min read