<p>Python 2.7<a href="http://docs.python.org/dev/library/collections.html#collections.OrderedDict" rel="nofollow noreferrer">docs for ^{<cd1>}</a>有一个指向在python2.4或更高版本上运行的<a href="http://code.activestate.com/recipes/576693/" rel="nofollow noreferrer">OrderedDict recipe</a>的链接。</p>
<p><strong>编辑:</strong>关于排序:使用<code>key=</code>,而不是<code>cmp=</code>。它往往会导致<a href="https://stackoverflow.com/questions/1972672/what-arguments-does-python-sort-function-have/1973688#1973688">faster code</a>,而且,Python3中的<code>cmp=</code>关键字已经被删除。</p>
<pre><code>d={5:6,7:8,100:101,1:2,3:4}
print(d.items())
# [(1, 2), (3, 4), (100, 101), (5, 6), (7, 8)]
</code></pre>
<p>您为<code>mycmp</code>发布的代码并没有明确您希望作为<code>x1</code>传递的内容。下面,我假设x1应该是每个键值对中的<strong>值</strong>。如果是这样,你可以这样做:</p>
<pre><code>length=4
print(sorted(d.items(),key=lambda item: abs(item[1]-length) ))
# [(3, 4), (1, 2), (5, 6), (7, 8), (100, 101)]
</code></pre>
<p><code>key=...</code>被传递一个函数,<code>lambda item: abs(item[1]-length)</code>。
对于<code>d.items()</code>中的每个<code>item</code>,lambda函数返回数字<code>abs(item[1]-length)</code>。就排序而言,此数字充当项目的代理。请参阅<a href="http://wiki.python.org/moin/HowTo/Sorting" rel="nofollow noreferrer">this essay</a>以获取有关在Python中排序习惯用法的更多信息。</p>
<p>PS.<code>len</code>是一个Python内置函数。为了不破坏<code>len</code>,我将变量名改为<code>length</code>。</p>