7

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?

Ram Narasimhan
  • 22,341
  • 5
  • 49
  • 55
user23634623
  • 151
  • 5
  • 11

1 Answers1

14

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}
timgeb
  • 76,762
  • 20
  • 123
  • 145