文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- Zoom.Quiet [2004-08-11 16:41:48]

1. 给字典排序

2.2 Sorting a Dictionary 给字典排序

Credit: Alex Martelli, Raymond Hettinger

1.1. 问题 Problem

You want to sort a dictionary. Because sorting is a concept that only makes sense for sequences, this presumably means that you want a sequence of the values of the dictionary in the order obtained by sorting the keys.

你想排序一个字典。因为排序是一个仅仅对序列有意义的概念。这大概意味着你想让字典的序列的值按照通过排列的键值顺序获得。

1.2. 解决 Solution

The simplest approach is to sort the items (i.e., key/value pairs), then pick just the values:

最简单的方法是排列元素(key/value对),然后挑出值:

   1 def sortedDictValues1(adict):
   2     items = adict.items(  )
   3     items.sort(  )
   4     return [value for key, value in items]

However, an alternative implementation that sorts just the keys, then uses them to index into the dictionary to build the result, happens to run more than twice as fast (for a dictionary of a few thousand entries) on my system:

然而,有一个可选择的仅仅排列键的实现, 那么使用他们去索引到字典构造结果。碰巧在我的系统上会快两倍(对于一个有上千条入口的字典)

   1 def sortedDictValues2(adict):
   2     keys = adict.keys(  )
   3     keys.sort(  )
   4     return [adict[key] for key in keys]

A further small speed-up (15% on my system) is to perform the last step by mapping a bound method. map is often marginally faster than a list comprehension when no lambda is involved:

一个更小的提速(在我的系统上是15%)是通过映射一个绑定的方法去执行最后一步。当不使用lambda的时候,Map经常比list内涵快:

   1 def sortedDictValues3(adict):
   2     keys = adict.keys(  )
   3     keys.sort(  )
   4     return map(adict.get, keys)

A really tiny extra speed-up (about 3% on my system) is available in Python 2.2 by using adict._ _getitem_ _ rather than adict.get in this latest, bound-method version.

一个真正小的额外提速(在我的系统大约是3%)是在python2.2中使用 ‘adict.getitem’ 来代替上一个版本里的 ‘adict.get’ 。

1.3. 讨论 Discussion

The concept of sorting applies only to a collection that has order梚n other words, a sequence. A mapping, such as a dictionary, has no order, so it cannot be sorted. And yet, "How do I sort a dictionary?" is a frequent question on the Python lists. More often than not, the question is about sorting some sequence of keys and/or values from the dictionary.

排序概念仅仅应用在一个有顺序的集合中。换句话说,是一个序列。一个映射,例如一个字典,没有顺序。所以它不能被排序。可是,“我怎么排序一个字典”是一个经常在python lists里问到的问题。时常地, 问题是关于从字典中排序一些键和(或)值的序列。

A dictionary's keys can be extracted as a list, which can then be sorted. The functions in this recipe return the values in order of sorted keys, which corresponds to the most frequent actual need when it comes to sorting a dictionary. Another frequent need is sorting by the values in the dictionary, for which you should see Recipe 17.7.

一个字典的键能够被抽取出来作为一个list,然后它能被排序。在这个配方里的函数返回按照排序的键的顺序的值。当它能够排序一个字典的时候,它与时常发生的实际需要相对应 。

The implementation choices are interesting. Because we are sorting key/value pairs by the key field and returning only the list of value fields, it seems conceptually simplest to use the first solution, which gets a list of the key/value pairs, sorts them, and then uses a list comprehension to pick the values. However, this is not the fastest solution. Instead, with Python 2.2, on dictionaries of a few thousand items, extracting just the keys, sorting them, and then accessing the dictionary for each key in the resulting list comprehension梩he second solution梐ppears to be over twice as fast.

实现的选择是有趣的。因为我们正在通过键的字段排序键/值对并且返回值字段的list。似乎最简单的概念是使用第一个解决方案,它得到一个键/值对的list。排序他们,然后使用一个list内涵去挑选值。然而这不是最快的解决方案。取而代之的是,在python2.2里,在一个上千条元素的字典上,仅仅抽取键,排序他们,然后在结果的list 内涵中为每一个键访问字典。第二个方案比第一个的快两倍。

This faster approach can be further optimized by extracting the bound method adict.get, which turns each key into its corresponding value, and then using the built-in function map to build the list by applying this callable to each item in the sorted list of keys. In Python 2.2, using adict._ _getitem_ _ rather than adict.get is even a little bit better (probably not enough to justify making your program version-dependent, but if you're already dependent on Python 2.2 for other reasons, you may as well use this approach).

这个快速的方法能够通过提取绑定的方法adict.get来优化。它返回一个每一个键到它的相对应的值,并且在排序的键的list上,使用内建函数map通过对每一个元素应用这个可调用的方法去构造一个列表

Simplicity is one the greatest virtues for any program, but the second and third solutions aren't really more complicated than the first; they are just, perhaps, a little bit more subtle. Those solutions are probably worth using to sort any dictionary, even though their performance advantages are really measurable only for very large ones.

简单对任何程序来说都是最伟大的艺术品。但是第二个和第三个方案没有第一个真正的复杂。他们仅仅,或许有一些微秒。这些方案可能是值得使用去排序任何字典。即使对非常大的字典来说。他们的性能优势是真的适当的。

1.4. 参考 See Also

Recipe 17.7 for another application of sorting on dictionaries.