[ACCEPTED]-How do I iterate over a Python dictionary, ordered by values?-python
sorted(dictionary.items(), key=lambda x: x[1])
for these of you that hate lambda :-)
import operator
sorted(dictionary.items(), key=operator.itemgetter(1))
However 1 operator
version requires CPython 2.5+
For non-Python 3 programs, you'll want to 7 use iteritems to get the performance boost 6 of generators, which yield values one at 5 a time instead of returning all of them 4 at once.
sorted(d.iteritems(), key=lambda x: x[1])
For even larger dictionaries, we 3 can go a step further and have the key function 2 be in C instead of Python as it is right now with 1 the lambda.
import operator
sorted(d.iteritems(), key=operator.itemgetter(1))
Hooray!
It can often be very handy to use namedtuple. For 8 example, you have a dictionary of name and 7 score and you want to sort on 'score':
import collections
Player = collections.namedtuple('Player', 'score name')
d = {'John':5, 'Alex':10, 'Richard': 7}
sorting 6 with lowest score first:
worst = sorted(Player(v,k) for (k,v) in d.items())
sorting with highest 5 score first:
best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
The order of 'key' and 'value' in 4 the listed tuples is (value, key), but now 3 you can get the name and score of, let's 2 say the second-best player (index=1) very 1 Pythonically like this:
player = best[1]
player.name
'Richard'
player.score
7
The items
method gives you a list of (key,value) tuples, which 3 can be sorted using sorted
and a custom sort key:
Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
>>> a={ 'a': 6, 'b': 1, 'c': 2 }
>>> sorted(a.items(), key=lambda (key,value): value)
[('b', 1), ('c', 2), ('a', 6)]
In 2 Python 3, the lambda expression will have 1 to be changed to lambda x: x[1]
.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.