Home Software Consultant

Exploring Counter and defaultdict in python collections

2013-05-05T14:24:29+00:00

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(, {'a': 1, 'c': 2, 'b': 1, 'l': 1, 'v': 1}) You can read more here http://docs.python.org/2/library/collections.html