Differences between revisions 3 and 6 (spanning 3 versions)
Revision 3 as of 2003-11-21 19:45:06
Size: 847
Editor: ip503dabc3
Comment: add name of pattern, reformat code and rename some variables
Revision 6 as of 2003-11-23 03:51:42
Size: 924
Editor: dsl254-010-130
Comment: (Simplified varname discussion.)
Deletions are marked like this. Additions are marked like this.
Line 17: Line 17:
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'' (DSU) pattern, or the ''Schwartzian transform'' if you're coming from Perl. 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.
Line 25: Line 25:
# variable named "dict_" because "dict" is a builtin.
Line 27: Line 28:
== Questions ==

This a good way? -- LionKimbro
(The variable was named {{{dict_}}} because {{{dict}}} is already a builtin.)

Sorting Lists of Dictionaries

Frequently you want to sort a list of dictionaries, based on some particular key.

For example:

   1 a = {"key1": 5 , "key2": 8, "key3": 2}
   2 b = {"key1": 7 , "key2": 4, "key3": 9}
   3 c = {"key1": 6 , "key2": 1, "key3": 1}
   4 undecorated = [a, b, c] # how do you sort this list?

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.

   1 sort_on = "key2"
   2 decorated = [(dict_[sort_on], dict_) for dict_ in undecorated]
   3 decorated.sort()
   4 sorted = [dict_ for (key, dict_) in l]
   5 # variable named "dict_" because "dict" is a builtin.

(The variable was named dict_ because dict is already a builtin.)

SortingListsOfDictionaries (last edited 2010-03-30 19:08:00 by wl-ol-s246-130)

Unable to edit the page? See the FrontPage for instructions.