Change language

# Counting frequencies in a list using a dictionary in Python

| | |

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 may be solved in different ways. A simple approach is to iterate over the list and use every single element of the list as the key of the dictionary, and store the corresponding counter of that key as values. Below is the Python code for this approach:

Exit :

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

Time complexity: O (N), where N — the length of the list.

Alternative way: An alternative approach would be to use the list.count () method. This makes the program much more compact without affecting the runtime. Below is the Python code for this:

 ` # Python program to calculate the frequency ` ` # of elements in a list using a dictionary `   ` def ` ` CountFrequency (my_list): `   ` # Create 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) `
 ` # Python program for calculating the frequency ` ` # of elements in list using a dictionary `   ` def ` ` CountFrequency (my_list): `   ` ` ` # Create 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) `

Exit:

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

Time complexity: O (N), where N — list length.