如何在Python 3.7中订购Counter/defaultdict?

jpp*_*jpp 7 python counter dictionary python-3.x defaultdict

我们知道在Python 3.6中,字典是作为实现细节排序的插入,并且可以依赖3.7插入顺序.

我希望这也适用于dict诸如collections.Counter和的子类collections.defaultdict.但这似乎只适用于defaultdict此案.

所以我的问题是:

  1. 维持订购是否属实defaultdict但不适用于Counter?如果是这样,是否有直接的解释?
  2. 是否应该dictcollections模块中这些子类的顺序视为实现细节?或者,例如,我们可以依赖defaultdictdictPython 3.7+ 那样的插入顺序吗?

以下是我的基本测试:

dict:有序

words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"]

dict_counter = {}
for w in words:
    dict_counter[w] = dict_counter.get(w, 0)+1

print(dict_counter)

# {'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2}
Run Code Online (Sandbox Code Playgroud)

反:无序

from collections import Counter, defaultdict

print(Counter(words))

# Counter({'apples': 3, 'kiwis': 2, 'oranges': 1, 'bananas': 1})
Run Code Online (Sandbox Code Playgroud)

defaultdict:ordered

dict_dd = defaultdict(int)
for w in words:
    dict_dd[w] += 1

print(dict_dd)

# defaultdict(<class 'int'>, {'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2})
Run Code Online (Sandbox Code Playgroud)

use*_*ica 9

Counter并且defaultdict现在都订购了,你可以依靠它.Counter只是因为它repr是在保证dict排序之前设计的,所以不看起来有序,并按Counter.__repr__值的降序对条目进行排序.

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))
Run Code Online (Sandbox Code Playgroud)

  • 这很棒.只是添加,可以通过`list(Counter(words))`来轻松测试,即返回插入顺序.谢谢! (2认同)