|
1 | 1 | # report.py |
2 | 2 | # |
3 | | -# Exercise 2.16 - Use method dict/zip for a flexible reading of csv |
4 | | - |
| 3 | +# Exercise 2.23 - Simplify read_portfolio with list comprenhesion |
| 4 | +# Extra feature: read_portfolio can read from csv with unwanted columns |
5 | 5 |
|
6 | 6 | import csv |
7 | 7 |
|
8 | 8 | def read_portfolio(filename): |
9 | 9 | '''Return portfolio in list of dictionaries''' |
10 | | - portfolio = [ ] |
11 | 10 |
|
12 | 11 | with open(filename, 'rt') as f: |
13 | 12 | rows = csv.reader(f) |
14 | 13 | headers = next(rows) |
15 | | - for row in rows: |
16 | | - # If we use dict+zip we broke script because all fields will be strings |
17 | | - # We need to cast field in 44 line to operate as a float |
18 | | - holding = dict(zip(headers, row)) |
19 | | - #holding = {"name": row[0], "shares":int(row[1]), "price":float(row[2])} |
20 | | - portfolio.append(holding) |
| 14 | + # Select on all CSV same columns |
| 15 | + select = ['name', 'shares', 'price'] |
| 16 | + indices = [ headers.index(colname) for colname in select ] |
| 17 | + portfolio = [ { colname: row[index] for colname, index in zip(select, indices) } for row in rows ] |
21 | 18 | return portfolio |
22 | 19 |
|
23 | 20 | def read_prices(filename): |
@@ -60,7 +57,7 @@ def get_headers(report): |
60 | 57 |
|
61 | 58 |
|
62 | 59 | prices = read_prices('Data/prices.csv') |
63 | | -portfolio = read_portfolio('Data/portfolio.csv') |
| 60 | +portfolio = read_portfolio('Data/portfoliodate.csv') |
64 | 61 | report = make_report(portfolio, prices) |
65 | 62 |
|
66 | 63 |
|
|
0 commit comments