|
5 | 5 | from pprint import pprint |
6 | 6 |
|
7 | 7 | def read_portfolio(filename): |
8 | | - portfolio = [] |
| 8 | + select = ['name', 'shares', 'price'] |
9 | 9 |
|
10 | 10 | f = open(filename) |
11 | 11 | rows = csv.reader(f) |
12 | 12 | headers = next(rows) |
| 13 | + indices = [ headers.index(colname) for colname in select ] |
13 | 14 |
|
14 | | - for rowno, row in enumerate(rows): |
15 | | - record = dict(zip(headers, row)) |
16 | | - try: |
17 | | - stocks = { |
18 | | - 'name' : record['name'], |
19 | | - 'shares' : int(record['shares']), |
20 | | - 'price' : float(record['price']) |
21 | | - } |
22 | | - portfolio.append(stocks) |
23 | | - except ValueError as e: |
24 | | - print(f"Row {rowno} Couldn't convert: {row}") |
| 15 | + try: |
| 16 | + portfolio = [ { colname: row[index] for colname, index in zip(select, indices) } for row in rows ] |
| 17 | + except ValueError as e: |
| 18 | + print(f"Row {rowno} Couldn't convert: {row}") |
| 19 | + |
| 20 | + #for rowno, row in enumerate(rows): |
| 21 | + # record = dict(zip(headers, row)) |
| 22 | + # try: |
| 23 | + #stocks = { |
| 24 | + # 'name' : record['name'], |
| 25 | + # 'shares' : int(record['shares']), |
| 26 | + # 'price' : float(record['price']) |
| 27 | + #} |
| 28 | + #portfolio.append(stocks) |
| 29 | + |
| 30 | + #except ValueError as e: |
| 31 | + # print(f"Row {rowno} Couldn't convert: {row}") |
25 | 32 |
|
26 | 33 | return portfolio |
27 | 34 |
|
@@ -68,11 +75,11 @@ def make_report(portfolio, prices): |
68 | 75 |
|
69 | 76 | #Calculating Gaing/Loss |
70 | 77 | for s in portfolio: |
71 | | - portfolio_with_change.append((s['name'], s['shares'], prices[s['name']] , prices[s['name']] - s['price'])) |
| 78 | + portfolio_with_change.append((s['name'], s['shares'], prices[s['name']] , float(prices[s['name']]) - float(s['price']))) |
72 | 79 |
|
73 | 80 | #Printing table |
74 | 81 | print('%10s %10s %10s %10s' % headers) |
75 | 82 | print(separator * len(headers)) |
76 | 83 | for name, shares, prices, change in portfolio_with_change: |
77 | 84 | prices_s = '$' + str(prices) |
78 | | - print(f'{name:>10s} {shares:>10d} {prices_s:>10s} {change:>10.2f}') |
| 85 | + print(f'{name:>10s} {shares:>10s} {prices_s:>10s} {change:>10.2f}') |
0 commit comments