Skip to content

Commit a27b565

Browse files
committed
Simplify read_portfolio function with list comprehension
1 parent f69d60a commit a27b565

1 file changed

Lines changed: 7 additions & 10 deletions

File tree

Work/report.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,20 @@
11
# report.py
22
#
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
55

66
import csv
77

88
def read_portfolio(filename):
99
'''Return portfolio in list of dictionaries'''
10-
portfolio = [ ]
1110

1211
with open(filename, 'rt') as f:
1312
rows = csv.reader(f)
1413
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 ]
2118
return portfolio
2219

2320
def read_prices(filename):
@@ -60,7 +57,7 @@ def get_headers(report):
6057

6158

6259
prices = read_prices('Data/prices.csv')
63-
portfolio = read_portfolio('Data/portfolio.csv')
60+
portfolio = read_portfolio('Data/portfoliodate.csv')
6461
report = make_report(portfolio, prices)
6562

6663

0 commit comments

Comments
 (0)