Count frequency of items in a list using Python

In this post I am going to show you how we can write a program in Python that can count the frequency of items in a list. First I shall implement it using the dictionary data structure in Python. Then I shall make it shorter (and nicer) using the defaultdict and Counter data structures from the collections module.

Here is our code that we will use to run and test the program -

if __name__ == "__main__":
    li = [2, 6, 9, 2, 8, 2, 9, 9, 3, 1, 4, 5, 7, 1, 8, 10, 2, 10, 10, 5]
    freq = frequency_counter(li)
    assert freq[1] == 2
    assert freq[2] == 4
    assert freq[3] == 1
    assert freq[11] == 0

Now let's look at the implementation using dictionary. We will iterate over all the items and then check if it exists in the dictionary. If it exists, we shall increase the count. And if it doesn't, then we shall set the count to 1.
def frequency_counter(li):
    freq_dt = dict()
    for item in li:
        if item in freq_dt:
            freq_dt[item] += 1
        else:
            freq_dt[item] = 1

    return freq_dt

defaultdict is a data sturcture very similar to dictionary (actually it extends the dictionary). The advantage is, you can create the dictionary using a default type, so when an item is not in the dictionary yet, the zero value of the default type would be used. Say 5 doesn't exist in the dictionary, the dt[5] would return 0. That's a huge convenience.
def frequency_counter(li):
    freq_dt = defaultdict(int)
    for item in li:
        freq_dt[item] += 1

    return freq_dt


Now let me introduce Counter, a special purpose dictionary. Instead of writing anything, showing code would be the best way -
def frequency_counter(li):
    freq_dt = Counter(li)
    return freq_dt


You can find the code here.

Comments

Popular posts from this blog

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code

Adjacency Matrix (Graph) in Python