<p>从Python 3.6开始,标准的<code>dict</code>类型默认保持插入顺序。</p>
<p>定义</p>
<pre><code>d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}
</code></pre>
<p>将生成一个字典,其中的键按源代码中列出的顺序排列。</p>
<p>这是通过在稀疏散列表中使用一个带有整数的简单数组来实现的,其中这些整数索引到另一个存储键值对(加上计算出的散列)的数组中。后一个数组恰好按插入顺序存储项,而整个组合实际使用的内存比Python3.5和之前使用的实现少。有关详细信息,请参见<a href="https://mail.python.org/pipermail/python-dev/2012-December/123028.html" rel="noreferrer">original idea post by Raymond Hettinger</a>。</p>
<p>在3.6中,这仍然被认为是一个实现细节;请参见<a href="https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-compactdict" rel="noreferrer"><em>What's New in Python 3.6</em> documentation</a>:</p>
<blockquote>
<p>The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).</p>
</blockquote>
<p>Python 3.7将这个实现细节提升到一个<em>语言规范</em>,因此现在必须<code>dict</code>在所有与该版本或更新版本兼容的Python实现中保持顺序。请参阅<a href="https://mail.python.org/pipermail/python-dev/2017-December/151283.html" rel="noreferrer">pronouncement by the BDFL</a>。</p>
<p>在某些情况下,您可能仍然希望使用<a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="noreferrer">^{<cd3>} class</a>,因为它在标准<code>dict</code>类型的基础上提供了一些附加功能。例如成为<a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Reversible" rel="noreferrer">reversible</a>(这扩展到<a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects" rel="noreferrer">view objects</a>),支持重新排序(通过<a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict.move_to_end" rel="noreferrer">^{<cd5>} method</a>)。</p>