我们知道在python3.6中,字典的插入顺序是作为实现细节的,而在3.7中,插入顺序是可以依赖的。
我希望这也适用于
dict
collections.Counter
和
collections.defaultdict
. 但这似乎只适用于
defaultdict
案例。
所以我的问题是:
-
是真的维持秩序吗
默认dict
但不是为了
Counter
? 如果是的话,有没有直接的解释?
-
你应该订购这些吗
中的子类
collections
依靠
在
默认dict
有秩序的
在Python 3.7+中?
以下是我的初步测试:
命令:命令
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})