prices.py changed on this slide
1# prices.py — nested data, read in one line
2ledger = {
3 "AAPL": {"shares": 10, "prices": [185.0, 188.2, 190.5]},
4 "NESN": {"shares": 4, "prices": [104.1, 103.0, 102.3]},
5 "VOO": {"shares": 2, "prices": [505.0, 509.9, 512.0]},
6}
7print(ledger["NESN"]["prices"][-1])
8print(ledger["AAPL"]["prices"][1:])
9
10last = {t: d["prices"][-1] for t, d in ledger.items()}
11values = [d["shares"] * last[t] for t, d in ledger.items()]
12rising = [t for t, d in ledger.items()
13 if d["prices"][-1] > d["prices"][0]]
14print(last)
15c = a copy of the outer dict onlyledger.copy()
16c["NESN"]["shares"] = 0changes an inner dict
17
18by_value = sorted(ledger, reverse=True,
19 key=lambda t: ledger[t]["shares"] * last[t])
20print(by_value, ledger["NESN"]["shares"])
21change = lambda p: (p[-1] - p[0]) / p[0]
22print({t: round(change(d["prices"]), 4)
23 for t, d in ledger.items()})
$ python prices.py
102.3
[188.2, 190.5]
{'AAPL': 190.5, 'NESN': 102.3, 'VOO': 512.0}
['AAPL', 'VOO', 'NESN'] 0
{'AAPL': 0.0297, 'NESN': -0.0173, 'VOO': 0.0139}