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.
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
|
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)
not a dictionary. note that the example creates a list, not a dictionary.
I'm not sure how new this feature is, but in Python 2.5 i use this:
Uh, yeah... Since the goal was to get something that's ordered, a list makes sense.
Deferring the sort to iteration is one technique but if you find yourself iterating often then it will kill performance. Python has a number of dictionary implementations that maintain the keys in sorted order. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. The SortedDict type is a drop-in replacement for Python's built-in dict type. There's also a performance comparison that benchmarks popular implementations against each other.