我们知道在Python 3.6中,字典以插入顺序作为实现细节,而在3.7中可以依赖插入排序。
我原本以为这也适用于dict
的子类,例如collections.Counter
和collections.defaultdict
。但是这似乎只对defaultdict
成立。
我的问题如下:
defaultdict
是否保持有序?而Counter
是否没有?如果是这样,是否有一个简单的解释?collections
模块中这些dict
子类的排序是否应被视为实现细节?例如,我们是否能够像在Python 3.7+中一样依赖于defaultdict
的插入顺序?
以下是我的基本测试结果:
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}
计数器:无序
from collections import Counter, defaultdict
print(Counter(words))
# Counter({'apples': 3, 'kiwis': 2, 'oranges': 1, 'bananas': 1})
defaultdict:有序
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})
list(Counter(words))
轻松测试,即插入顺序将被返回。谢谢! - jpp