Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count items in list and make it a dictionary [duplicate]

I am trying to generate a dictionary from the list

names = ['tango', 'bravo', 'tango', 'alpha', 'alpha']

The result is supposed to look like this:

{'tango': 2 , 'bravo': 1 , 'alpha': 2}

How would I be able to do that?

like image 798
user23634623 Avatar asked Dec 28 '15 17:12

user23634623


1 Answers

This is exactly what a Counter is for.

>>> from collections import Counter
>>> Counter(['tango', 'bravo', 'tango', 'alpha', 'alpha'])
Counter({'tango': 2, 'alpha': 2, 'bravo': 1})

You can use the Counter object just like a dictionary, because it is a child class of the builtin dict. Excerpt from the docs:

class Counter(__builtin__.dict)
Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.

edit:

As requested, here's another way:

>>> names = ['tango', 'bravo', 'tango', 'alpha', 'alpha']
>>> d = {}
>>> for name in names:
...     d[name] = d.get(name, 0) + 1
... 
>>> d
{'bravo': 1, 'tango': 2, 'alpha': 2}
like image 50
timgeb Avatar answered Sep 29 '22 10:09

timgeb