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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With