Python Forum

Full Version: Presenting data from a dictionary in a basic table
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Requirement: present keys and values from a dictionary w/ headers via a __str__ method. Also present an additional value calculated in an earlier method ('total_STK').

Error being encountered now| AttributeError: 'Useful' object has no attribute 'total_STK'

class ExampleBase:
    def __init__(self, company_name="N/A", stock_dict={}):
        """
        class constructor
        """
        self.company_name = company_name
        self.stock_dict = stock_dict
        print(self.stock_dict)       
        return


class Useful(ExampleBase):
    """
    Inherits from ExampleBase class
    """
    def __init__(self, stock_dict):
        super().__init__(stock_dict)
        return
    

    def compute_value(self, stock_dict):
        """
        Computes value of stk
        """
        total_STK = sum(v1*v2 for v1,v2 in stock_dict.values())
        return
    
    def __str__(self):
        """
        Prints a table of dates and stocks
        """        
        str = "Keys \t Values \n %s %s %d" %\
            (self.stock_dict.keys(),
             self.stock_dict.values(),
             self.total_STK
             )
        return str
    

##
## Program starts running from here
##
if __name__ == "__main__":
    a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)}
    b = ExampleBase("Bern", a)
    d = Useful(b)
    d.compute_value(a)
    print(d)
on line 25, change to:
        self.total_STK = sum(v1*v2 for v1,v2 in stock_dict.values())
Thanks @Larzo60+!
That did the trick.

Any idea on how to print the dictionary keys and values in columns inside the __str__ method?

With the way my code is written now the output I get is:
Keys Values
dict_keys([]) dict_values([])
for key, value in self.stock.items():
    print('key: {}, value: {}'.format(key, value)
to pring any individual fields in value, you can use value['itemname']