tags:

views:

1134

answers:

3

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?

+8  A: 
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+

vartec
I need the keys and the items, not just the items.
mike
dictionary.items() gives you both the keys and values, not just the keys.
Eli Courtwright
@Mike: items are (key, value) pairs.
vartec
..or `key = operator.itemgetter(1)`.
John Fouhy
+2  A: 

The items method gives you a list of (key,value) tuples, which 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 Python 3, the lambda expression will have to be changed to lambda x: x[1].

Barry Wark
You might want to remove the first three lines and the last one...looks a little busy right now.
Nikhil Chelliah
Note that tuple unpacking is no longer supported in Python 3... unfortunately.
Stephan202
@Nikhil I think the header is important. Especially per @Stephan's comment, it's significant which version I'm using for the demo.
Barry Wark
@Barry: isn't it clear from your syntax what version are you using?
SilentGhost
+2  A: 

For non-Python 3 programs, you'll want to use iteritems to get the performance boost of generators, which yield values one at a time instead of returning all of them at once.

sorted(d.iteritems(), key=lambda x: x[1])

For even larger dictionaries, we can go a step further and have the key function be in C instead of Python as it is right now with the lambda.

import operator
sorted(d.iteritems(), key=operator.itemgetter(1))

Hooray!

Hao Lian
Oooh. Nice with the operator.itemgetter. Sweet.
Barry Wark