Open In App

Counting the frequencies in a list using dictionary in Python

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an unsorted list of some elements(which may or may not be integers), Find the frequency of each distinct element in the list using a Python dictionary.

Example:

Input:  [1, 1, 1, 5, 5, 3, 1, 3, 3, 1,
                  4, 4, 4, 2, 2, 2, 2]
Output:  1 : 5
         2 : 4
         3 : 3
         4 : 3
         5 : 2
Explanation: Here 1 occurs 5 times, 2 
              occurs 4 times and so on...

The problem can be solved in many ways. A simple approach would be to iterate over the list and use each distinct element of the list as a key of the dictionary and store the corresponding count of that key as values. Below is the Python code for this approach:

Approach 1: Counting the frequencies in a list using a loop

In this method, we will use a Python loop to count the distinct element from the list and append it to the dictionary.

Python3




def CountFrequency(my_list):
 
    # Creating an empty dictionary
    freq = {}
    for item in my_list:
        if (item in freq):
            freq[item] += 1
        else:
            freq[item] = 1
 
    for key, value in freq.items():
        print("% d : % d" % (key, value))
 
 
# Driver function
if __name__ == "__main__":
    my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
 
    CountFrequency(my_list)


Output: 

 1 :  5
 2 :  4
 3 :  3
 4 :  3
 5 :  2

Time Complexity: O(N), where N is the length of the list.

Approach 2: Count the frequencies in a list using  list.count() 

An alternative approach can be to use the list.count() method. 

Python3




import operator
 
 
def CountFrequency(my_list):
 
    # Creating an empty dictionary
    freq = {}
    for items in my_list:
        freq[items] = my_list.count(items)
 
    for key, value in freq.items():
        print("% d : % d" % (key, value))
 
 
# Driver function
if __name__ == "__main__":
    my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
    CountFrequency(my_list)


Output: 

 1 :  5
 2 :  4
 3 :  3
 4 :  3
 5 :  2

Time Complexity: O(N2), where N is the length of the list. The time complexity list.count() is O(N) alone, and when used inside the loop it will become O(N2). 

Approach 3: Count the frequencies in a list using dict.get()

The dict.get() method, makes the program much shorter and makes understanding how the get method is useful instead of if…else. 

Python3




def CountFrequency(my_list):
 
    # Creating an empty dictionary
    count = {}
    for i in [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]:
        count[i] = count.get(i, 0) + 1
    return count
 
 
# Driver function
if __name__ == "__main__":
    my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
    print(CountFrequency(my_list))


Output: 

{1: 5, 5: 2, 3: 3, 4: 3, 2: 4}

Related Article: Count frequencies of all elements in array in Python using collections module

Count the frequencies in a list using  operator.countOf() method

Approach 4: 

  1. Created a dictionary with keys as unique list values and values as unique element count in list using for loop and operator.countOf() method.
  2. Displayed the keys and values of the dictionary.

Python3




import operator
 
def CountFrequency(my_list):
 
    # Creating an empty dictionary
    freq = {}
    for items in my_list:
        freq[items] = operator.countOf(my_list, items)
 
    for key, value in freq.items():
        print("% d : % d" % (key, value))
 
# Driver function
if __name__ == "__main__":
    my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
    CountFrequency(my_list)


Output

 1 :  5
 5 :  2
 3 :  3
 4 :  3
 2 :  4

Time Complexity : O(N*N) 
N -length of list
Auxiliary Space : O(1)



Similar Reads

Javascript program for counting frequencies of array elements
In this article, we are given an array that may contain duplicate values. We will print all elements and their frequencies if the duplicates exist. We can do this by using two methods: Running two loopsUsing HashingUsing the Binary search functionExamples: Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}Output : 10 3 20 4 5 1Input : arr[] = {10, 20,
4 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 the frequency of each character same. Input : str =
2 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 performed. Counting Associated Values Frequencies in Dict
5 min read
Python - Frequencies of Values in a Dictionary
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 = {'i
4 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python - Cumulative Row Frequencies in List
Given Matrix, the task is to write a Python program to get total counts of occurrences from the row. Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]], ele_list = [1, 2, 7] Output : [2, 2, 2, 5] Explanation : 2 occurs 2 times in row 1 and so on. Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4]], ele_list =
4 min read
Count frequencies of all elements in array in Python using collections module
Given an unsorted array of n integers which can contains n integers. Count frequency of all elements that are present in array. Examples: Input : arr[] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5] Output : 1 -> 4 2 -> 4 3 -> 2 4 -> 1 5 -> 2 This problem can be solved in many ways, refer Count frequencies of all elements in array link. I
2 min read
Python | Counting sign change in list containing Positive and Negative Integers
Given a list containing Positive and Negative integers, We have to find number of times the sign(Positive or Negative) changes in the list. Input: [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] Output:9 Explanation : Sign change from -1 to 2, ans = 1 Sign change from 3 to -4, ans = 2 Sign change from -4 to 5, ans = 3 Sign change from 5 to -6, ans = 4
5 min read
three90RightbarBannerImg