0

Essentially I'm writing a function that receives a list as input and returns a dictionary that counts how many times the data in the list is repeated.

#Example:
count_occurrences(["a", "b", "c", "a", "a," "b"])

#output: 
{"a" : 3, "b" : 2, "c": 1}

My solution so far has been:

def count_occurrences(a_list):
    count_list = {}
    for i in a_list:
        if i not in count_list:
            count_list[i] = 1
        else: 
            count_list[i] += 1 
    return count_list 

But I'm wondering if there's a way to use Dictionary Comprehension to shorten/optimize this script.

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40

1 Answers1

0

There is a built-in class made specifically for this. It's called a Counter and it already implements a dict to you don't need to convert it.

from collections import Counter

print(Counter(["a", "b", "c", "a", "a", "b"]))

#Output
Counter({'a': 3, 'b': 2, 'c': 1})
Martin
  • 619
  • 5
  • 13