ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Sorting dictionaries by value in Python 2.4
Submitter: Nick Coghlan (other recipes)Nick Coghlan (other recipes)
Last Updated: 2004/09/13
Version no: 1.0
Category: Searching

 

5 stars 2 vote(s)


Description:

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.

Source: Text Source

# 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)



Add comment

Number of comments: 3

not a dictionary, stewart midwinter, 2007/01/02
note that the example creates a list, not a dictionary.
Add comment

Uh, yeah..., steve charlesworth, 2008/02/19
Since the goal was to get something that's ordered, a list makes sense.
Add comment

C T, 2007/05/22
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

Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Treat the Win32 Registry ...

4. Watching a directory ...

5. Union Find data structure

6. Function Decorators by ...

7. MS SQL Server log monitor

8. Table objects with ...

9. wx twisted support using ...

10. More accurate sum




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.