Python | Count keys with particular value in dictionary
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 dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}# printing original dictionaryprint("The original dictionary : " + str(test_dict))# Initialize valueK = 2# Using loop# Selective key values in dictionaryres = 0for key in test_dict: if test_dict[key] == K: res = res + 1 # printing resultprint("Frequency of K is : " + str(res)) |
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3Method #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 dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}# printing original dictionaryprint("The original dictionary : " + str(test_dict))# Initialize valueK = 2# Using sum() + values()# Selective key values in dictionaryres = sum(x == K for x in test_dict.values()) # printing resultprint("Frequency of K is : " + str(res)) |
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3Method #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 dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2}# printing original dictionaryprint("The original dictionary : " + str(test_dict))# Initialize valueK = 2# Using count() + values()list1=list(test_dict.values())# Selective key values in dictionaryres = list1.count(K) # printing resultprint("Frequency of K is : " + str(res)) |
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3Complexity Analysis:
In all the solutions time and space complexity are the same:
Time Complexity: O(n)
Space Complexity: O(n)



.png)