You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -30,7 +32,9 @@ It seems simple enough. However, how do we sort a list of dicts?
30
32
31
33
By what criteria?
32
34
33
-
You can guide the sorting by using a *key function*. The *key function* is a function that receives the dictionary and returns the value in a specific key.
35
+
You can guide the sorting by using a *key function*. The *key
36
+
function* is a function that receives the dictionary and returns the
37
+
value of interest for sorting.
34
38
35
39
```python
36
40
defstock_name(s):
@@ -39,7 +43,7 @@ def stock_name(s):
39
43
portfolio.sort(key=stock_name)
40
44
```
41
45
42
-
The value returned by the *key function* determines the sorting.
46
+
Here's the result.
43
47
44
48
```python
45
49
# Check how the dictionaries are sorted by the `name` key
@@ -56,13 +60,16 @@ The value returned by the *key function* determines the sorting.
56
60
57
61
### Callback Functions
58
62
59
-
Callback functions are often short one-line functions that are only used for that one operation. For example of previous sorting example.
60
-
Programmers often ask for a short-cut, so is there a shorter way to specify custom processing for `sort()`?
63
+
In the above example, the key function is an example of a callback
64
+
function. The `sort()` method "calls back" to a function you supply.
65
+
Callback functions are often short one-line functions that are only
66
+
used for that one operation. Programmers often ask for a short-cut
67
+
for specifying this extra processing.
61
68
62
69
### Lambda: Anonymous Functions
63
70
64
-
Use a lambda instead of creating the function.
65
-
In our previous sorting example.
71
+
Use a lambda instead of creating the function. In our previous
72
+
sorting example.
66
73
67
74
```python
68
75
portfolio.sort(key=lambdas: s['name'])
@@ -156,6 +163,6 @@ Try sorting the portfolio according to the price of each stock
156
163
157
164
Note: `lambda` is a useful shortcut because it allows you to
158
165
define a special processing function directly in the call to `sort()` as
159
-
opposed to having to define a separate function first (as in part a).
166
+
opposed to having to define a separate function first.
0 commit comments