Size: 969
Comment: dict_ explanation
|
Size: 924
Comment: (Simplified varname discussion.)
|
Deletions are marked like this. | Additions are marked like this. |
Line 25: | Line 25: |
# variable named "dict_" because "dict" is a builtin. | |
Line 27: | Line 28: |
In case you're wondering, the variable is named `dict_` because we want to have Wiki:MeaningfulNames, but we don't want to shadow the `dict` builtin, so we append an underscore. | (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:
Toggle line numbers
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.
(The variable was named dict_ because dict is already a builtin.)