我有一本字典:
{ 'a': 6, 'b': 1, 'c': 2 }
我想按价值迭代它,而不是按键.换一种说法:
(b, 1) (c, 2) (a, 6)
什么是最直接的方式?
sorted(dictionary.items(), key=lambda x: x[1])
对于那些讨厌lambda的人:-)
import operator sorted(dictionary.items(), key=operator.itemgetter(1))
但是operator
版本需要CPython 2.5+
对于非Python 3程序,您将需要使用iteritems来提高生成器的性能,这样可以一次生成一个值,而不是一次返回所有生成器.
sorted(d.iteritems(), key=lambda x: x[1])
对于更大的字典,我们可以更进一步,将关键函数放在C而不是Python中,就像现在使用lambda一样.
import operator sorted(d.iteritems(), key=operator.itemgetter(1))
万岁!
It can often be very handy to use namedtuple. For example, you have a dictionary of name and score and you want to sort on 'score':
import collections Player = collections.namedtuple('Player', 'score name') d = {'John':5, 'Alex':10, 'Richard': 7}
sorting with lowest score first:
worst = sorted(Player(v,k) for (k,v) in d.items())
sorting with highest score first:
best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
The order of 'key' and 'value' in the listed tuples is (value, key), but now you can get the name and score of, let's say the second-best player (index=1) very Pythonically like this:
player = best[1] player.name 'Richard' player.score 7