擅长:python、mysql、java
<p>不,没有直接的方法,因为Python字典没有集合顺序。</p>
<p>从<a href="http://docs.python.org/2/library/stdtypes.html#dict.items" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.</p>
</blockquote>
<p>换言之,<code>b</code>的“索引”完全取决于之前插入和删除的映射:</p>
<pre><code>>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}
</code></pre>
<p>从Python2.7开始,如果插入顺序对应用程序很重要,则可以使用<a href="http://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">^{<cd2>} type</a>。</p>