How are Counter / defaultdict ordered in Python 3.7?

后端 未结 1 1009
星月不相逢
星月不相逢 2020-12-20 15:06

We know in Python 3.6 dictionaries are insertion ordered as an implementation detail, and in 3.7 insertion ordering can be relied upon.

I expected this to also be th

相关标签:
1条回答
  • 2020-12-20 15:59

    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))
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题