ActiveState Code

Recipe 304440: Sorting dictionaries by value in Python 2.4


Python 2.4 adds a new builtin function sorted(), which can make obtaining the items of a dictionary sorted by key or value a single line operation.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Example from PEP 265 - Sorting Dictionaries By Value
#    Counting occurences of letters

d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}

# operator.itemgetter is new in Python 2.4
#  `itemgetter(index)(container)` is equivalent to `container[index]`
from operator import itemgetter

# Items sorted by key
#   The new builtin `sorted()` will return a sorted copy of the input iterable.
print sorted(d.items())

# Items sorted by key, in reverse order
#   The keyword argument `reverse` operates as one might expect
print sorted(d.items(), reverse=True)

# Items sorted by value
#    The keyword argument `key` allows easy selection of sorting criteria
print sorted(d.items(), key=itemgetter(1))

# In-place sort still works, and also has the same new features as sorted
items = d.items()
items.sort(key = itemgetter(1), reverse=True)
print items

Discussion

The new 'sorted' builtin is a convenient expression replacement for the old statement based approach to obtaining a sorted copy.

The new keyword arguments to the sort operations are extremely handy for tasks such as sorting a dictionary by value (see the "Sort names and separate by last initial" recipe for a more involved use of the new features)

Comments

  1. 1. At 4:03 p.m. on 2 jan 2007, stewart midwinter said:

    not a dictionary. note that the example creates a list, not a dictionary.

  2. 2. At 1:02 a.m. on 22 may 2007, C T said:

    I'm not sure how new this feature is, but in Python 2.5 i use this:

    di = d.items()
    if b_sorted:
        di.sort()  # by first item
    
    if b_ranked:
        di.sort(key=lambda x: x[1])  # by second item
    
  3. 3. At 2:22 p.m. on 19 feb 2008, steve charlesworth said:

    Uh, yeah... Since the goal was to get something that's ordered, a list makes sense.

Sign in to comment