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.
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.
OutputThe 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)]
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.
OutputThe 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)]
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.
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.
Output[({'gfg': 1, 'is': 4, 'best': 9}, 2), ({'gfg': 6, 'is': 3, 'best': 8}, 2), ({'gfg': 1, 'is': 1, 'best': 9}, 1)]
Output[({'is': 4, 'gfg': 1, 'best': 9}, 2), ({'gfg': 6, 'is': 3, 'best': 8}, 2), ({'is': 1, 'gfg': 1, 'best': 9}, 1)]