|
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
d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}
from operator import itemgetter
print sorted(d.items())
print sorted(d.items(), reverse=True)
print sorted(d.items(), key=itemgetter(1))
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)
|