I needed to count frequency of items in a list. Given a list like below
some_data = ['a','b','v','c','l','c']
The ugly way was using the dictionary
[gist id=”5520902″]
The end result is
{'a': 1, 'c': 2, 'b': 1, 'l': 1, 'v': 1}
But we can use Counter which is much cleaner
[gist id=”5520864″]
Result –
Counter({'c': 2, 'a': 1, 'b': 1, 'l': 1, 'v': 1})
But, more elegant, as suggested in comments by Andy
[gist id=5567806]
And, another way is using defaultdict
[gist id=5520913]
Result
defaultdict(
You can read more here http://docs.python.org/2/library/collections.html
2 replies on “Exploring Counter and defaultdict in python collections”
You can use Counter more elegantly by simply passing it the list:
Counter(some_data)
Awesome!