mike mike - 1 year ago 59
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?

Answer Source
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+

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download