Exercise 10.2
Introduction
Use your report
module to read some stock portfolio data (the same
code you’ve seen many times already).
>>> import report
>>> portfolio = report.read_portfolio('Data/portfolio.csv')
>>> for s in portfolio:
print s
... inspect the contents ...
>>>
(a) Sorting on a field
Try the following statements which sort the portfolio data alphabetically by stock name.
>>> def stock_name(s):
return s['name']
>>> portfolio.sort(key=stock_name)
>>> for s in portfolio:
print s
... inspect the result ...
>>>
In this part, the stock_name()
function extracts the name of a stock from
a single entry in the portfolio
list. sort()
uses the result of
this function to do the comparison.
(b) Sorting on a field with lambda
Try sorting the portfolio according the number of shares using a
lambda
expression:
>>> portfolio.sort(key=lambda s: s['shares'])
>>> for s in portfolio:
print s
... inspect the result ...
>>>
Try sorting the portfolio according to the price of each stock
>>> portfolio.sort(key=lambda s: s['price'])
>>> for s in portfolio:
print s
... inspect the result ...
>>>
Note: lambda
is a useful shortcut because it allows you to
define a special processing function directly in the call to sort()
as
opposed to having to define a separate function first (as in part a).