I am trying to create a portfolio class. I want to zip my two lists into a dictionary but when a i try to print it out, it is empty(even though my lists are not). Am i missing something??
import numpy as np
class Portfolio(object):
"""description of class"""
array_of_stock_prices=[]
array_of_stock_names=[]
#create a dictionary of stocks
stocks=dict(zip(array_of_stock_names,array_of_stock_prices))
def __init__(self):
print()
def AddStock(self,stock_ticker,stock_price):
self.array_of_stock_names.append(stock_ticker)
self.array_of_stock_prices.append(stock_price)
def printObject(self):
for key,value in self.stocks.items():
print(key,value)
port1=Portfolio()
port1.AddStock('AApl',100)
port1.printObject()
kgf3JfUtW
15.2k12 gold badges63 silver badges92 bronze badges
asked Dec 4, 2017 at 14:48
brain_dead_cow
835 silver badges14 bronze badges
1 Answer 1
You create the dictionary only once, with empty lists. If you want to keep it up to date, put that line of code after every extension of the lists (in the end of AddStock), and keep this dictionary as an attribute of self, like
self.stocks = dict(zip(self.array_of_stock_names, self.array_of_stock_prices))
answered Dec 4, 2017 at 14:50
Uriel
16.3k6 gold badges29 silver badges48 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
stocksonly once.Addstocki.e. the dict is created before your lists have any values. None of your functions modifies the dictionary, so it remains empty.array_of_stock_prices, ` array_of_stock_names` andstocksare class attributes (shared between all instances of the class). I don't think that's what you want.