Frequency of element in a list using Dictionary

Suppose a list of number is available to you. you are requested to find out the frequency of these elements available in this list using a dictionary.

Dictionary is a data type available in python that can contain unsorted items using keys. The combination of key and value define a dictionary. After the execution of your program, the output should look like this.

list1 = [1, 2, 3, 4, 5, 6, 7, 34, 2, 2, 2, 4, 6, 7, 7, 8, 9] 
and its output is like
{1: 1, 2: 4, 3: 1, 4: 2, 5: 1, 6: 2, 7: 3, 34: 1, 8: 1, 9: 1}

where first define the element in the list and the second element defines the frequency of that element in the list.

There are more than one method available to solve this problem, one of the solution is like this

count frequency of element using a dictionary – method -1

# program to find out frequency of each element in a list using dictionary
#   made by           : rakesh kumar

list1 = [1, 2, 3, 4, 5, 6, 7, 34, 2, 2, 2, 4, 6, 7, 7, 8, 9]
freq = {}
for x in list1:
    if x in freq:
        freq[x] += 1
    else:
        freq[x] = 1

print(freq)

above code pick one element from the list at a time and check whether that element exists in the dictionary or not if this element already exists then increase the counting by one otherwise add the same element with counting one.

The output of the above code is as follows

rakesh@folio MINGW64 ~
$ C:/Python37/python.exe c:/Users/rakesh/Desktop/dict-01.py
{1: 1, 2: 4, 3: 1, 4: 2, 5: 1, 6: 2, 7: 3, 34: 1, 8: 1, 9: 1}

count frequency of element using a dictionary – method -2

# program to find out frequency of each element in a list using dictionary
#   made by           : rakesh kumar

# altername method to find out
list1 = [1, 2, 3, 4, 5, 6, 7, 34, 2, 2, 2, 4, 6, 7, 7, 8, 9]
freq = {}
for x in list1:
    if x not in freq:
        freq[x] = list1.count(x)

print(freq)

Here we are using list count method() to find out frequency of the element in a list and saving the save in a dictionary.

The output of the above program is as follows

$ C:/Python37/python.exe c:/Users/rakesh/Desktop/dict-01.py
{1: 1, 2: 4, 3: 1, 4: 2, 5: 1, 6: 2, 7: 3, 34: 1, 8: 1, 9: 1}

Now check the code inside an online Python interpreter and see the results

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.