Python – Frequencies of Values in a Dictionary
Last Updated : 25 Apr, 2023
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
from collections import defaultdict test_dict = { 'ide' : 3 , 'Gfg' : 3 , 'code' : 2 } print ("The original dictionary : " + str (test_dict)) res = defaultdict( int ) for key, val in test_dict.items(): res[val] + = 1 print ("The frequency dictionary : " + str ( dict (res))) |
Output: The original dictionary : {'Gfg': 3, 'code': 2, 'ide': 3} The frequency dictionary : {2: 1, 3: 2}
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
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
from collections import Counter test_dict = { 'ide' : 3 , 'Gfg' : 3 , 'code' : 2 } print ("The original dictionary : " + str (test_dict)) res = Counter(test_dict.values()) print ("The frequency dictionary : " + str ( dict (res))) |
Output: The original dictionary : {'code': 2, 'Gfg': 3, 'ide': 3} The frequency dictionary : {2: 1, 3: 2}
Method #3 : Using values(),count(),list(),set() methods
Approach
- Create an empty dictionary res, store the values of dictionary in a list x(list(),values())
- Store the unique values of a list x in list y(using list(),set())
- Initiate a for loop to traverse unique values list y
- Inside for loop with unique value as key and count of unique value in list y as value(using count())
- Display output dictionary res
Python3
test_dict = { 'ide' : 3 , 'Gfg' : 3 , 'code' : 2 } print ( "The original dictionary : " + str (test_dict)) res = dict () x = list (test_dict.values()) y = list ( set (x)) for i in y: res[i] = x.count(i) print ( "The frequency dictionary : " + str (res)) |
Output The original dictionary : {'ide': 3, 'Gfg': 3, 'code': 2} The frequency dictionary : {2: 1, 3: 2}
Time Complexity: O(N), where N is the length of dictionary values list
Auxiliary Space: O(N)
Method #4: Using values(),operator.countOf(),list(),set() methods
Step-by-step approach:
- Create an empty dictionary res, store the values of dictionary in a list x(list(),values())
- Store the unique values of a list x in list y(using list(),set())
- Initiate a for loop to traverse unique values list y
- Inside for loop with unique value as key and count of unique value in list y as value(using operator.countOf())
- Display output dictionary res
Below is the implementation of the above approach:
Python3
test_dict = { 'ide' : 3 , 'Gfg' : 3 , 'code' : 2 } print ( "The original dictionary : " + str (test_dict)) res = dict () x = list (test_dict.values()) y = list ( set (x)) import operator for i in y: res[i] = operator.countOf(x,i) print ( "The frequency dictionary : " + str (res)) |
Output The original dictionary : {'ide': 3, 'Gfg': 3, 'code': 2} The frequency dictionary : {2: 1, 3: 2}
Time Complexity: O(N), where N is the length of dictionary values list
Auxiliary Space: O(N)
Similar Reads
Get Key from Value in Dictionary - Python
The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
6 min read
Python dictionary values()
values() method in Python is used to obtain a view object that contains all the values in a dictionary. This view object is dynamic, meaning it updates automatically if the dictionary is modified. If we use the type() method on the return value, we get "dict_values object". It must be cast to obtain
2 min read
Counting Frequency of Values by Date in Pandas
Counting the frequency of values by date is a common task in time-series analysis, where we need to analyze how often certain events occur within specific time frames. Understanding these frequencies can provide valuable insights if we analyze sales data, website traffic, or any other date-related d
3 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
How to Add Same Key Value in Dictionary Python
Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python. Adding
2 min read
Find Frequency of Characters in Python
In this article, we will explore various methods to count the frequency of characters in a given string. One simple method to count frequency of each character is by using a dictionary. Using DictionaryThe idea is to traverse through each character in the string and keep a count of how many times it
2 min read
Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a ke
5 min read
Python Dictionary Exercise
Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
3 min read
Find frequency of each word in a string in Python
Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi A
7 min read
Python dictionary, set and counter to check if frequencies can become same
Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = âxyyzâ Output : Yes We can remove character âyâ from above string to make th
2 min read