Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading