mike mike - 4 months ago 5x
Python Question

How do I iterate over a Python dictionary, ordered by values?

I've got a dictionary like:

{ 'a': 6, 'b': 1, 'c': 2 }

I'd like to iterate over it by value, not by key. In other words:

(b, 1)
(c, 2)
(a, 6)

What's the most straightforward way?

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 operator version requires CPython 2.5+