Python | Count keys with particular value in dictionary
Last Updated :
15 May, 2023
Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it's occurrence. Let's discuss certain ways in which this problem can be solved.
Method #1: Using loop This problem can be solved using naive method of loop. In this we just iterate through each key in dictionary and when a match is found, the counter is increased.
Python3
# Python3 code to demonstrate working of
# Count keys with particular value in dictionary
# Using loop
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize value
K = 2
# Using loop
# Selective key values in dictionary
res = 0
for key in test_dict:
if test_dict[key] == K:
res = res + 1
# printing result
print("Frequency of K is : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2: Using sum() + values() This can also be solved using the combination of sum() and value(). In this, sum is used to perform the summation of values filtered and values of dictionary are extracted using values()
Python3
# Python3 code to demonstrate working of
# Count keys with particular value in dictionary
# Using sum() + values()
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize value
K = 2
# Using sum() + values()
# Selective key values in dictionary
res = sum(x == K for x in test_dict.values())
# printing result
print("Frequency of K is : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #3 : Using count() and values().These methods can be used together to find number of keys with particular value.
Python3
# Python3 code to demonstrate working of
# Count keys with particular value in dictionary
# Using count() + values()
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize value
K = 2
# Using count() + values()
list1=list(test_dict.values())
# Selective key values in dictionary
res = list1.count(K)
# printing result
print("Frequency of K is : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
Time Complexity: O(n)
Auxiliary Space : O(n)
Method #4: Using lambda functions
Python3
# Python3 code to demonstrate working of
# Count keys with particular value in dictionary
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize value
K = 2
keys = list(test_dict.keys())
res = len(list(filter(lambda x: test_dict[x] == K, keys)))
# printing result
print("Frequency of K is : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using collections.Counter()
Python3
# Python3 code to demonstrate working of
# Count keys with particular value in dictionary
# Using collections.Counter()
# Importing collections for Counter
import collections
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize value
K = 2
# Using collections.Counter()
res = collections.Counter(test_dict.values())[K]
# printing result
print("Frequency of K is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #6: Using operator.countOf() method:
Python3
# Python3 code to demonstrate working of
# Count keys with particular value in dictionary
import operator as op
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize value
K = 2
# Using count() + values()
list1=list(test_dict.values())
# Selective key values in dictionary
res = op.countOf(list1,K)
# printing result
print("Frequency of K is : " + str(res))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 7: Using a dictionary comprehension
Step-by-step approach:
- Create a new dictionary using a dictionary comprehension that counts the occurrence of values in the original dictionary.
- Create another dictionary using a dictionary comprehension that counts the occurrence of keys with a particular value in the original dictionary.
- Access the value of the key equal to the given value K in the second dictionary to get the frequency
Python3
# Initialize dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
# Initialize value
K = 2
# Create a new dictionary with count of values as keys
count_dict = {v: list(test_dict.values()).count(v) for v in set(test_dict.values())}
# Create a new dictionary with count of keys with particular value as values
freq_dict = {v: sum(1 for k in test_dict.keys() if test_dict[k] == v) for v in count_dict.keys()}
# Access the frequency of K
res = freq_dict[K]
# printing result
print("Frequency of K is : " + str(res))
OutputFrequency of K is : 3
Time complexity: O(n^2)
Auxiliary space: O(n)
Similar Reads
Python Print Dictionary Keys and Values
When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values.Example: Using print() MethodPythonmy_dict = {'a': 1, 'b': 2, 'c': 3} print("Keys:", l
2 min read
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key.For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'fo
3 min read
Get Values of Particular Key in List of Dictionaries - Python
We are given a list of dictionaries and a particular key. Our task is to retrieve the values associated with that key from each dictionary in the list. If the key doesn't exist in a dictionary, it should be ignored. For example, if we have the following list of dictionaries and we want to extract th
2 min read
Python - Dictionary with Index as Value
We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}.Using Dictionary ComprehensionWe can use dictionary comprehens
2 min read
Python - Count if dictionary position equals key or value
Given a dictionary, count instances where dictionary item position equals key or value. Valid for Py >= 3.6 [ Introduction of dictionary ordering ]. Input : test_dict = {5:3, 2:3, 10:4, 7:3, 8:1, 9:5} Output : 2 Explanation : At 3 and 5th position, values are 3 and 5. Input : test_dict = {5:3, 2:
3 min read
Count the Key from Nested Dictionary in Python
In Python, counting the occurrences of keys within a nested dictionary often requires traversing through its complex structure. In this article, we will see how to count the key from the nested dictionary in Python. Count the Key from the Nested Dictionary in PythonBelow are some ways and examples b
4 min read
Python program to group keys with similar values in a dictionary
Given a dictionary with values as a list. Group all the keys together with similar values. Input : test_dict = {"Gfg": [5, 6], "is": [8, 6, 9], "best": [10, 9], "for": [5, 2], "geeks": [19]} Output : [['Gfg', 'is', 'for'], ['is', 'Gfg', 'best'], ['best', 'is'], ['for', 'Gfg']] Explanation : Gfg has
2 min read
Python | Find keys with duplicate values in dictionary
Given a dictionary, the task is to find keys with duplicate values. Let's discuss a few methods for the same. Method #1: Using Naive approach In this method first, we convert dictionary values to keys with the inverse mapping and then find the duplicate keys Python3 # Python code to demonstrate # fi
4 min read
Python - Check for Key in Dictionary Value list
Sometimes, while working with data, we might have a problem we receive a dictionary whose whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let's discuss certain ways in which this task can be performed. Method #1: Using any() Th
6 min read
Python | Initialize dictionary with None values
Sometimes, while working with dictionaries, we might have a utility in which we need to initialize a dictionary with None values so that they can be altered later. This kind of application can occur in cases of memoization in general or competitive programming. Let's discuss certain ways in which th
4 min read