2

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()
7
  • When you create the dictionary, the lists are empty Commented Dec 4, 2017 at 14:50
  • You initialize stocks only once. Commented Dec 4, 2017 at 14:50
  • 1
    your stocks dictionary is created before your call to Addstock i.e. the dict is created before your lists have any values. None of your functions modifies the dictionary, so it remains empty. Commented Dec 4, 2017 at 14:55
  • WARNING your array_of_stock_prices, ` array_of_stock_names` and stocks are class attributes (shared between all instances of the class). I don't think that's what you want. Commented Dec 4, 2017 at 14:57
  • Also, why do you want to maintain two lists and a dict instead of a single dict ? This violates the SPOT rule (=>"Single Point Of Truth"). Commented Dec 4, 2017 at 14:59

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.