Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Frequencies of Values in a Dictionary

  • Last Updated : 01 Oct, 2020

Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_dict = {‘ide’ : 3, ‘Gfg’ : 3, ‘code’ : 2}
Output : {3: 2, 2: 1}

Input : test_dict = {10 : 1, 20 : 2, 30 : 1, 40 : 2 }
Output : {1 : 2, 2 : 2}

Method #1 : Using defaultdict() + loop
The combination of above functions can be used to solve this problem. In this, we use defaultdict() to initialize the counter dictionary with integers and increment counter in brute force manner using loop.




# Python3 code to demonstrate working of 
# Dictionary Values Frequency
# Using defaultdict() + loop
from collections import defaultdict
  
# initializing dictionary
test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Dictionary Values Frequency
# Using defaultdict() + loop
res = defaultdict(int)
for key, val in test_dict.items():
    res[val] += 1
      
# printing result 
print("The frequency dictionary : " + str(dict(res))) 
Output:
The original dictionary : {'Gfg': 3, 'code': 2, 'ide': 3}
The frequency dictionary : {2: 1, 3: 2}

Method #2 : Using Counter() + values()
The combination of above functions can be used to solve this problem. In this, we perform the task of extraction of values using values() and frequency counter using Counter().




# Python3 code to demonstrate working of 
# Dictionary Values Frequency
# Using Counter() + values()
from collections import Counter
  
# initializing dictionary
test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Dictionary Values Frequency
# Using defaultdict() + loop
res = Counter(test_dict.values())
      
# printing result 
print("The frequency dictionary : " + str(dict(res))) 
Output:
The original dictionary : {'code': 2, 'Gfg': 3, 'ide': 3}
The frequency dictionary : {2: 1, 3: 2}

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!