After I made my post How to Group and Count with Dictionaries, I noticed there was something nice I could have added. That was how to make a counter class that also remembers the order in which it first found something. It is super easy (pun intended) to do in Python. See the following.
from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): pass
This code works because of the method resolution order. You can easily find out 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 all of the dictionary methods will come OrderedDict
instead of dict
giving us the result we want.
You can use this method of inheritance on any class that inherits from dict
where you want to keep the order of its key as that in which they are inserted. In the more general case, you can use it to create a new class that uses an alternative implementation of some interface.
For more information on this, there is an excellent post by Raymond Hettinger called Python’s super() considered super! that goes into all this in way more detail.