网站开发过什么软件,遵义在线读者板留言,wordpress企业自适应,网站建设的五个基本要素自python3.7以来#xff0c;python的dict都会保留插入顺序#xff0c;那么相关的defaultdict, Counter#xff0c;以及使用json.load、json.dump也一定能保持顺序吗#xff1f;
结论#xff1a;以上这些和dict一样#xff0c;都会保留插入顺序
defaultdict#xff1a;…自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