The Python Oracle

How are Counter / defaultdict ordered in Python 3.7?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops

--

Chapters
00:00 Question
01:35 Accepted answer (Score 16)
02:09 Thank you

--

Full question
https://stackoverflow.com/questions/5217...

Accepted answer links:
[Counter.__repr__]: https://github.com/python/cpython/blob/v...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #dictionary #counter #defaultdict

#avk47



ACCEPTED ANSWER

Score 18


Counter and defaultdict are both ordered now, and you can rely on it. Counter just doesn't look ordered because its repr was designed before dict ordering was guaranteed, and Counter.__repr__ sorts entries by descending order of value.

def __repr__(self):
    if not self:
        return '%s()' % self.__class__.__name__
    try:
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)
    except TypeError:
        # handle case where values are not orderable
        return '{0}({1!r})'.format(self.__class__.__name__, dict(self))