Python Forum
Presenting data from a dictionary in a basic table
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Presenting data from a dictionary in a basic table
#1
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)
Reply
#2
on line 25, change to:
        self.total_STK = sum(v1*v2 for v1,v2 in stock_dict.values())
Reply
#3
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([])
Reply
#4
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']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Changing the content of the table and saving the new data into another file femke_pythonquestion123 1 1,564 Sep-18-2020, 12:06 PM
Last Post: femke_pythonquestion123
  Read data from a CSV file in S3 bucket and store it in a dictionary in python Rupini 3 6,966 May-15-2020, 04:57 PM
Last Post: snippsat
  printing data from dictionary kiki1113 4 45,939 Nov-20-2017, 04:43 PM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020