Both Counter and defaultdict(int) can work fine here, but there are few differences between them:
-
Countersupports most of the operations you can do on a multiset. So, if you want to use those operation then go for Counter. -
Counterwon’t add new keys to the dict when you query for missing keys. So, if your queries include keys that may not be present in the dict then better useCounter.
Example:
>>> c = Counter()
>>> d = defaultdict(int)
>>> c[0], d[1]
(0, 0)
>>> c
Counter()
>>> d
defaultdict(<type 'int'>, {1: 0})
Example:
Counteralso has a method calledmost_commonthat allows you to sort items by their count. To get the same thing indefaultdictyou’ll have to usesorted.
Example:
>>> c = Counter('aaaaaaaaabbbbbbbcc')
>>> c.most_common()
[('a', 9), ('b', 7), ('c', 2)]
>>> c.most_common(2) #return 2 most common items and their counts
[('a', 9), ('b', 7)]
Counteralso allows you to create a list of elements from the Counter object.
Example:
>>> c = Counter({'a':5, 'b':3})
>>> list(c.elements())
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b']
So, depending on what you want to do with the resulting dict you can choose between Counter and defaultdict(int).