forked from dabeaz-course/python-mastery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadport.py
47 lines (34 loc) · 1.13 KB
/
readport.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import csv
from collections import Counter
def read_portfolio(filename):
portfolio = []
with open(filename) as f:
rows = csv.reader(f)
headers = next(rows) # grab first line as column headings
for row in rows:
record = {
'name': row[0],
'shares': int(row[1]),
'price': float(row[2])
}
portfolio.append(record)
return portfolio
if __name__ == '__main__':
portfolio = read_portfolio('Data/portfolio.csv')
print('holidings > 100 shares')
print([s for s in portfolio if s['shares'] > 100])
print('total value of all shares')
print(sum(s['shares'] * s['price'] for s in portfolio))
print('all unique stock names')
print({s['name'] for s in portfolio})
print('all holdings')
print([s['name'] for s in portfolio])
print('Count the total shares of each stock')
total = {s['name']: 0 for s in portfolio}
for s in portfolio:
total[s['name']] += s['shares']
print(total)
totals = Counter()
for s in portfolio:
totals[s['name']] += s['shares']
print(totals)