The Catch

How to Create an Ordered Counter class in Python

by Michael

After I made my post How to Group and Count with Dictionaries I noticed there was something nice I could have added in. How to make a counter class that also remembers the order in which it first found something. It super easy to do in Python, see the following.

from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): pass

This works because of the method resolution order. You can find out really easy what that is by trying help(OrderedCounter) into the python console. I have reproduced what you would get for Counter and OrderedCounter below.

""" Counter | Method resolution order: | Counter | __builtin__.dict | __builtin__.object OrderedCounter | Method resolution order: | OrderedCounter | collections.Counter | collections.OrderedDict | __builtin__.dict | __builtin__.object """

What has changed is that now OrderedDict has been inserted in the order in which methods which be searched for when using OrderedCounter just before dict. So any of the dictionary methods will come OrderedDict instead of dict giving us the result we want.

This can be used on any class that inherits from dict and you want to keep the order of its key as that in which they are inserted. And in the more general case it can be used to create a new class uses and alternative implementation of some interface.

For more information on this, there is a great post by Raymond Hettinger called Python’s super() considered super! that goes into all this in way more detail.

If you found this interesting you might want to