Python - Values frequencies of key
Last Updated :
05 May, 2023
Sometimes, while working with Python dictionary lists, one can have a problem in which we require to find the frequency of all the values occurring in a specific key in dictionary list. This can have application across many domains including web development. Let's discuss certain ways in which this task can be performed.
Input : test_list = [{'gfg': [1]}, {'good': [5, 78, 10], 'gfg': [5, 6, 7, 8]}] Output : {8: 1, 1: 1, 5: 1, 6: 1, 7: 1} Input : test_list = [{'gfg': [1, 5, 6, 7]}] Output : {1: 1, 5: 1, 6: 1, 7: 1}
Method #1 : Using Counter() + list comprehension The combination of above functionalities is used to solve this problem. In this, we perform the task of finding frequency using Counter() and computation is done using list comprehension.
Python3
# Python3 code to demonstrate working of
# Values frequencies of key
# Using Counter() + list comprehension
from collections import Counter
# initializing list
test_list = [{'gfg' : [1, 5, 6, 7], 'is' : [9, 6, 2, 10]},
{'gfg' : [5, 6, 7, 8], 'good' : [5, 7, 10]},
{'gfg' : [7, 5], 'best' : [5, 7]}]
# printing original list
print("The original list is : " + str(test_list))
# frequency key
freq_key = "gfg"
# Values frequencies of key
# Using Counter() + list comprehension
res = Counter([idx for val in test_list for idx in val[freq_key]])
# printing result
print("The frequency dictionary : " + str(dict(res)))
Output :
The original list is : [{'gfg': [1, 5, 6, 7], 'is': [9, 6, 2, 10]}, {'gfg': [5, 6, 7, 8], 'good': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}] The frequency dictionary : {8: 1, 1: 1, 5: 3, 6: 2, 7: 3}
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using chain.from_iterables() + Counter() The combination of above methods can be used to solve this problem. In this, we perform the task of iteration and binding using chain.from_iterables().
Python3
# Python3 code to demonstrate working of
# Values frequencies of key
# Using chain.from_iterables() + Counter()
from collections import Counter
import itertools
# initializing list
test_list = [{'gfg' : [1, 5, 6, 7], 'is' : [9, 6, 2, 10]},
{'gfg' : [5, 6, 7, 8], 'good' : [5, 7, 10]},
{'gfg' : [7, 5], 'best' : [5, 7]}]
# printing original list
print("The original list is : " + str(test_list))
# frequency key
freq_key = "gfg"
# Values frequencies of key
# Using chain.from_iterables() + Counter()
res = Counter(itertools.chain.from_iterable([sub[freq_key] for sub in test_list]))
# printing result
print("The frequency dictionary : " + str(dict(res)))
Output :
The original list is : [{'gfg': [1, 5, 6, 7], 'is': [9, 6, 2, 10]}, {'gfg': [5, 6, 7, 8], 'good': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}] The frequency dictionary : {8: 1, 1: 1, 5: 3, 6: 2, 7: 3}
Time Complexity: O(n*n) where n is the number of elements in the dictionary. The chain.from_iterables() + Counter() is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the dictionary.
Method #3 : Using extend(),list(),set(),count() methods
Approach
- Extracting all values of a particular key in list of dictionaries using for loop and extend() method
- Create a new list with all unique values of above values list
- Now create a dictionary with unique value as key and count of this value in the values list using count() method
- Display dictionary
Python3
# Python3 code to demonstrate working of
# Values frequencies of key
# initializing list
test_list = [{'gfg' : [1, 5, 6, 7], 'is' : [9, 6, 2, 10]},
{'gfg' : [5, 6, 7, 8], 'good' : [5, 7, 10]},
{'gfg' : [7, 5], 'best' : [5, 7]}]
# printing original list
print("The original list is : " + str(test_list))
# frequency key
freq_key = "gfg"
# Values frequencies of key
res = dict()
x=[]
for i in test_list:
x.extend(i[freq_key])
y=list(set(x))
for i in y:
res[i]=x.count(i)
# printing result
print("The frequency dictionary : " + str(res))
OutputThe original list is : [{'gfg': [1, 5, 6, 7], 'is': [9, 6, 2, 10]}, {'gfg': [5, 6, 7, 8], 'good': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}]
The frequency dictionary : {1: 1, 5: 3, 6: 2, 7: 3, 8: 1}
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #4:Using Numpy
Algorithm
- Initialize the list of dictionaries.
- Print the original list.
- Initialize the frequency key for which we want to find the values frequency.
- Initialize an empty dictionary for storing the frequency of values of the frequency key.
- For each dictionary in the list, extend the values corresponding to the frequency key to a list x.
- Get the unique values of list x using set().
- For each unique value in the list of unique values, count the frequency of the value in the list x using count() function and store the frequency in the resultant dictionary.
- Print the frequency dictionary.
Python3
import numpy as np
# initializing list
test_list = [{'gfg': [1, 5, 6, 7], 'is': [9, 6, 2, 10]},
{'gfg': [5, 6, 7, 8], 'good': [5, 7, 10]},
{'gfg': [7, 5], 'best': [5, 7]}]
# printing original list
print("The original list is:", test_list)
# frequency key
freq_key = "gfg"
# Values frequencies of key
res = {}
flat_arr = np.concatenate([d[freq_key] for d in test_list])
unique, counts = np.unique(flat_arr, return_counts=True)
for i in range(len(unique)):
res[unique[i]] = counts[i]
# printing result
print("The frequency dictionary:", res)
#This code is contributed by Vinay Pinjala.
Output
The original list is: [{'gfg': [1, 5, 6, 7], 'is': [9, 6, 2, 10]}, {'gfg': [5, 6, 7, 8], 'good': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}]
The frequency dictionary: {1: 1, 5: 3, 6: 2, 7: 3, 8: 1}
The time complexity of the given code is O(N*M), where N is the number of dictionaries in the list and M is the maximum length of the list associated with the given frequency key.
The space complexity of the given code is also O(N*M), since we are creating a list to store all the values associated with the given frequency key, and then creating a dictionary with keys as unique values and their count as values.
Method 5 : Using a loop
step-by-step approach:
- Initialize an empty dictionary called "freq_dict" to store the frequency count of each value in the "gfg" key.
- Loop through each dictionary in the list "test_list".
- Access the values of the "gfg" key in the current dictionary using the syntax "current_dict['gfg']".
- Loop through each value in the "gfg" key using a for loop.
- For each value in the "gfg" key, check if it is already a key in the "freq_dict" dictionary. If it is, increment its value by 1. If it is not, add it as a new key with value 1.
- After iterating through all the dictionaries in "test_list", "freq_dict" will contain the frequency count of each value in the "gfg" key.
- Print the "freq_dict" dictionary.
Python3
# initializing list
test_list = [{'gfg': [1, 5, 6, 7], 'is': [9, 6, 2, 10]},
{'gfg': [5, 6, 7, 8], 'good': [5, 7, 10]},
{'gfg': [7, 5], 'best': [5, 7]}]
# printing original list
print("The original list is:", test_list)
# frequency key
freq_key = "gfg"
# initialize frequency dictionary
freq_dict = {}
# loop through each dictionary in test_list
for d in test_list:
# loop through each value in the "gfg" key
for val in d[freq_key]:
# update frequency count
if val in freq_dict:
freq_dict[val] += 1
else:
freq_dict[val] = 1
# printing result
print("The frequency dictionary:", freq_dict)
OutputThe original list is: [{'gfg': [1, 5, 6, 7], 'is': [9, 6, 2, 10]}, {'gfg': [5, 6, 7, 8], 'good': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}]
The frequency dictionary: {1: 1, 5: 3, 6: 2, 7: 3, 8: 1}
Time complexity: O(N*M), where N is the number of dictionaries in "test_list" and M is the average length of the "gfg" key in each dictionary.
Auxiliary space: O(K), where K is the number of unique values in the "gfg" key across all dictionaries in "test_list".
Similar Reads
Python - Keys Values equal frequency
Given a dictionary, count instances where keys are equal to values. Input : test_dict = {5:5, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 2 Explanation : At 2 instances, keys are equal to values.Input : test_dict = {5:4, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 1 Explanation : At 1 instance, key is equal to valu
4 min read
Python - Values Frequency Index List
Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of
4 min read
Python - False values Frequency
Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization like in data Science. Lets discuss certain ways
5 min read
Python - Frequency of K in sliced String
Given a String, find the frequency of certain characters in the index range. Input : test_str = 'geeksforgeeks is best for geeks', i = 3, j = 9, K = 'e' Output : 0 Explanation : No occurrence of 'e' between 4th [s] and 9th element Input : test_str = 'geeksforgeeks is best for geeks', i = 0, j = 9, K
6 min read
Python - Unique values count of each Key
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 ha
7 min read
Frequency of Numbers in String - Python
We are given a string and we have to determine how many numeric characters (digits) are present in the given string. For example: "Hello123World456" has 6 numeric characters (1, 2, 3, 4, 5, 6).Using re.findall() re.findall() function from the re module is a powerful tool that can be used to match sp
3 min read
Python - Sort rows by Frequency of K
Given a Matrix, the task is to write a Python program to perform sorting on rows depending on the frequency of K. Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]], K = 2 Output : [[5, 5, 4, 7, 7, 4], [1, 2], [10, 2, 3, 2, 3], [1, 1, 2, 2, 2]] Explanation : 0 < 1
4 min read
Python | Finding frequency in list of tuples
In python we need to handle various forms of data and one among them is list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the 1st element in list of tuple which can be extended to any index. Let's discuss cert
6 min read
Python - Test for Unique Frequencies
Given a list, find if frequencies of each element of values are in itself unique values. Input : test_list = [4, 3, 2] Output : False Explanation : All have 1 as frequency, hence duplicacy, hence False Input : test_list = [4, 3, 3, 2, 2, 2] Output : True Explanation : 1, 2, 3 are frequencies of 4, 3
7 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