DEV Community

Cover image for Python's Collections Module: Why dictionaries maintain insertion order but printing Counter doesn't?
Kathan Vakharia
Kathan Vakharia

Posted on

Python's Collections Module: Why dictionaries maintain insertion order but printing Counter doesn't?

Do dictionaries in python maintain insertion order?

Well if your answer was NO, time to update your python knowledge because they do maintain their insertion order in python 3.6+ and completely from python 3.7+

image

But a Counter object doesn't,

from collections import Counter 

nums = [1, 1, 2, 2, 2, 3, 5, 5, 5]

#You would expect the order of counts,
# to be 1->2->3->5
print(Counter(nums))

"""Output: But it didn't work that way!

Counter({2: 3, 5: 3, 1: 2, 3: 1})
"""
Enter fullscreen mode Exit fullscreen mode

Why printing Counter doesn't maintain insertion order despite the fact it is a dict sub-class?

The reason behind this is the __repr__ method implementation of Counter object.
The __repr__ method decides object's representation when displaying it using print() function.

image

Don't worry if above definition looks complex at first sight :)

Let's try to get insights from this method definition,

Focus on the code inside the try block because that's what decides what happens while we print a Counter.

Aha! we can see the call to most_common method and that's what causing the descending order. MYSTERY SOLVED🔥 or is it?

image

But...

You might have a doubt. Considering Counter is infact a sub class of builtins.dict, why it doesn't obey dictionary class's __repr__ and maintain insertion order 🤔

The Method Resolution Order (MRO)

To put it simply, MRO defines the order in which python interpreter searches a method for a particular object,

image

Method Resolution Order can be found using ClassName.__mro__ attribute or calling help on that Class.

It is evident that, __repr__ of Counter's priority is higher than that of builtins.dict and that's the reason while printing Counter object doesn't maintain insertion order.

Then how the heck Counter can maintain insertion order when printing it 😐, How about you find yourself? OR as always

STAY TUNED for the next post 😉

Top comments (0)