877
Comment: l should be decorated
|
1390
see also
|
Deletions are marked like this. | Additions are marked like this. |
Line 24: | Line 24: |
sorted = [dict_ for (key, dict_) in decorated] | result = [dict_ for (key, dict_) in decorated] |
Line 28: | Line 28: |
Starting with Py2.4 the {{{list.sort()}}} method provides a {{{key=}}} argument for doing the transform in a single step. The new {{{sorted()}}} built-in function goes a step further and encapsulates making a new sorted list while leaving the original intact. Also, the new {{{operator.itemgetter()}}} function helps by constructing functions for key access: {{{ >>> from operator import itemgetter >>> result = sorted(undecorated, key=itemgetter('key2')) }}} == See Also == * ["HowTo/Sorting"] |
Sorting Lists of Dictionaries
Frequently you want to sort a list of dictionaries, based on some particular key.
For example:
There are many ways to do this. Here's the fastest way to do it, as it avoids using a custom comparison function, instead using builtin comparisons. This is the decorate-sort-undecorate pattern, or the Schwartzian transform if you're coming from Perl.
(The variable was named dict_ because dict is already a builtin.)
Starting with Py2.4 the list.sort() method provides a key= argument for doing the transform in a single step. The new sorted() built-in function goes a step further and encapsulates making a new sorted list while leaving the original intact. Also, the new operator.itemgetter() function helps by constructing functions for key access:
>>> from operator import itemgetter >>> result = sorted(undecorated, key=itemgetter('key2'))
See Also
- ["HowTo/Sorting"]