Python - Values frequency across Dictionaries lists
Last Updated :
13 Apr, 2023
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 : test_list1 = [{"Gfg" : 6}], test_list2 = [{"a" : 6}, {"b" : 6}, {"d" : 6}}]
Output : {'Gfg': 3}
Explanation : 6 has 3 occurrence in 2nd list.
Method #1: Using dictionary comprehension + count() + list comprehension
The combination of above functionalities can be used to solve this problem. In this, we perform this task using 2 steps, in first we extract all values from second list, and then perform mapping with frequency with first dictionary using list comprehension and count().
Python3
# Python3 code to demonstrate working of
# Values frequency across Dictionaries lists
# Using list comprehension + dictionary comprehension + count()
# initializing lists
test_list1 = [{"Gfg" : 6}, {"is" : 9}, {"best" : 10}]
test_list2 = [{"a" : 6}, {"b" : 10}, {"c" : 9}, {"d" : 6}, {"e" : 9}, {"f" : 9}]
# printing original list
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# extracting values from target dictionary
temp = [val for sub in test_list2 for key, val in sub.items()]
# frequency mapping from 1st dictionary keys
res = {key : temp.count(val) for sub in test_list1 for key, val in sub.items()}
# printing result
print("The frequency dictionary : " + str(res))
OutputThe original list 1 : [{'Gfg': 6}, {'is': 9}, {'best': 10}]
The original list 2 : [{'a': 6}, {'b': 10}, {'c': 9}, {'d': 6}, {'e': 9}, {'f': 9}]
The frequency dictionary : {'Gfg': 2, 'is': 3, 'best': 1}
Time complexity: O(n^2), where n is the total number of elements in both the input lists.
Auxiliary space: O(n), where n is the total number of elements in both the input lists.
Method #2: Using dictionary comprehension + operator.countOf() + list comprehension
The combination of above functionalities can be used to solve this problem. In this, we perform this task using 2 steps, in first we extract all values from second list, and then perform mapping with frequency with first dictionary using list comprehension and operator.countOf().
Python3
# Python3 code to demonstrate working of
# Values frequency across Dictionaries lists
# Using list comprehension + dictionary comprehension + operator.countOf()
import operator as op
# initializing lists
test_list1 = [{"Gfg" : 6}, {"is" : 9}, {"best" : 10}]
test_list2 = [{"a" : 6}, {"b" : 10}, {"c" : 9}, {"d" : 6}, {"e" : 9}, {"f" : 9}]
# printing original list
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# extracting values from target dictionary
temp = [val for sub in test_list2 for key, val in sub.items()]
# frequency mapping from 1st dictionary keys
res = {key : op.countOf(temp,val) for sub in test_list1 for key, val in sub.items()}
# printing result
print("The frequency dictionary : " + str(res))
OutputThe original list 1 : [{'Gfg': 6}, {'is': 9}, {'best': 10}]
The original list 2 : [{'a': 6}, {'b': 10}, {'c': 9}, {'d': 6}, {'e': 9}, {'f': 9}]
The frequency dictionary : {'Gfg': 2, 'is': 3, 'best': 1}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: Using a nested for loop
This program counts the frequency of values from the first list of dictionaries in the second list of dictionaries, and stores the results in a dictionary. The output is the frequency dictionary.
Python3
# Python3 code to demonstrate working of
# Values frequency across Dictionaries lists
# Using nested for loop
# initializing lists
test_list1 = [{"Gfg" : 6}, {"is" : 9}, {"best" : 10}]
test_list2 = [{"a" : 6}, {"b" : 10}, {"c" : 9}, {"d" : 6}, {"e" : 9}, {"f" : 9}]
# printing original list
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# empty dictionary to store the result
res = {}
# iterate through each dictionary in test_list1
for dict1 in test_list1:
# iterate through each key-value pair in the dictionary
for key1, val1 in dict1.items():
count = 0
# iterate through each dictionary in test_list2
for dict2 in test_list2:
# iterate through each key-value pair in the dictionary
for key2, val2 in dict2.items():
# check if the value is equal to the value in test_list1
if val2 == val1:
count += 1
res[key1] = count
# printing result
print("The frequency dictionary : " + str(res))
OutputThe original list 1 : [{'Gfg': 6}, {'is': 9}, {'best': 10}]
The original list 2 : [{'a': 6}, {'b': 10}, {'c': 9}, {'d': 6}, {'e': 9}, {'f': 9}]
The frequency dictionary : {'Gfg': 2, 'is': 3, 'best': 1}
Time complexity: O(n^3), where n is the length of the longer of the two input lists.
Auxiliary space: O(1) or constant.
Method #6: Using defaultdict
Another way to solve this problem is by using the defaultdict class from the collections module.
Step by step:
- Import the defaultdict class from the collections module.
- Initialize a defaultdict object with a default value of 0.
- Use a nested for loop to iterate through each dictionary in test_list1 and each key-value pair in the dictionary.
- Inside the nested for loop, use another nested for loop to iterate through each dictionary in test_list2 and each key-value pair in the dictionary.
- Check if the value of the current key-value pair in test_list1 is equal to the value of the current key-value pair in test_list2.
- If the values are equal, increment the corresponding key in the defaultdict object by 1.
- Convert the defaultdict object to a regular dictionary using the dict() constructor.
- Print the resulting dictionary.
Python3
from collections import defaultdict
# initializing lists
test_list1 = [{"Gfg" : 6}, {"is" : 9}, {"best" : 10}]
test_list2 = [{"a" : 6}, {"b" : 10}, {"c" : 9}, {"d" : 6}, {"e" : 9}, {"f" : 9}]
# initialize a defaultdict object with a default value of 0
res = defaultdict(int)
# iterate through each dictionary in test_list1
for dict1 in test_list1:
# iterate through each key-value pair in the dictionary
for key1, val1 in dict1.items():
# iterate through each dictionary in test_list2
for dict2 in test_list2:
# iterate through each key-value pair in the dictionary
for key2, val2 in dict2.items():
# check if the value is equal to the value in test_list1
if val2 == val1:
# increment the corresponding key in the defaultdict object by 1
res[key1] += 1
# convert the defaultdict object to a regular dictionary
res = dict(res)
# print the resulting dictionary
print("The frequency dictionary : " + str(res))
OutputThe frequency dictionary : {'Gfg': 2, 'is': 3, 'best': 1}
Time complexity: O(n^2), where n is the length of test_list1 multiplied by the length of test_list2.
Auxiliary space: O(k), where k is the number of unique values in test_list1.
Similar Reads
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 - Convert Frequency dictionary to list When we convert a frequency dictionary to a list, we are transforming the dictionary into a list of key-value or just the keys/values, depending on needs. We can convert a frequency dictionary to a list using methods such as list comprehension, loops, extend() method and itertools.chain() function.F
3 min read
Python - Convert list of dictionaries to Dictionary Value list We are given a list of dictionaries we need to convert it to dictionary. For example, given a list of dictionaries: d = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}], the output should be: {'a': [1, 3, 5], 'b': [2, 4, 6]}.Using Dictionary ComprehensionUsing dictionary comprehension, we can
3 min read
Increment value in dictionary - Python In Python, dictionaries store data as keyâvalue pairs. If a key already exists, its value can be updated or incremented. This is commonly used for counting occurrences, like word frequency or item counts. Let's discuss certain ways in which this task can be performed. Using defaultdict()defaultdict
3 min read
Python Program to calculate Dictionaries frequencies 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,
6 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