自python3.7以来,python的dict都会保留插入顺序,那么相关的defaultdict, Counter,以及使用json.load
、json.dump
也一定能保持顺序吗?
结论:以上这些和dict一样,都会保留插入顺序
defaultdict:
文档中说明了defaultdict只重载了dict的__getitem__
方法,并增加了一个default_factory
属性,未修改其他部分,所以和普通的dict一样,拥有保持顺序的特性。
参见https://docs.python.org/3.8/library/collections.html#defaultdict-objects
Counter:官方明确表明保持顺序
Changed in version 3.7: As a dict subclass, Counter Inherited the capability to remember insertion order. Math operations on Counter objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand.
参见https://docs.python.org/3.8/library/collections.html
json:官方明确表明保持顺序
Note This module’s encoders and decoders preserve input and output order by default. Order is only lost if the underlying containers are unordered.
Prior to Python 3.7, dict was not guaranteed to be ordered, so inputs and outputs were typically scrambled unless collections.OrderedDict was specifically requested. Starting with Python 3.7, the regular dict became order preserving, so it is no longer necessary to specify collections.OrderedDict for JSON generation and parsing.
参见https://docs.python.org/3.8/library/json.html