Convert list with repeated values to a dictionary

I am looking for an efficient way to take a list that has several elements with 2 or more occurrences, and convert into a dictionary where the value equals the number of occurrences.

Example list:

l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog']

l_dict = {'dog':4, 'bird': 3, 'cat': 4, 'fish': 1}

Any suggestions is appreciated. Thanks.

>Solution :

here’s a 1 liner for this purpose using the Counter function from collections library:

from collections import Counter
l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog']

print(Counter(l))

Leave a Reply