Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 537
mike Avatar asked Mar 23 '09 17:03

mike


People also ask

Can you iterate through values in a dictionary Python?

You can iterate through a Python dictionary using the keys(), items(), and values() methods. keys() returns an iterable list of dictionary keys. items() returns the key-value pairs in a dictionary. values() returns the dictionary values.

How do you iterate through a list in dictionary?

You can simply iterate over the range of length of list. In the outer loop, we use range and length function to create a list that we can iterate through. We use the index value to get each dictionary. In the inner loop, we use key variable to iterate through the current dictionary.

Can you iterate over a dictionary?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.


4 Answers

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+

like image 109
vartec Avatar answered Sep 25 '22 20:09

vartec


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!

like image 41
hao Avatar answered Sep 27 '22 20:09

hao


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
like image 39
Remi Avatar answered Sep 26 '22 20:09

Remi


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].

like image 22
Barry Wark Avatar answered Sep 24 '22 20:09

Barry Wark