Dictionary Calculation - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Dictionary Calculation (/thread-17730.html) |
Dictionary Calculation - prophet11 - Apr-22-2019 Dear Programmers, I have an inquiry: I need to calculate the earnings for these list of stocks inside a dictionary. The calculation is as followed: Profit/Loss = (Current Value - Purchase Price) X No Stocks Could you please help me understand why my code is not working. # convert my list from previous assigment to dictionary x = [("stock1", 125, 772.88, 941.53), ("stock2", 85, 56.60, 73.04), ("stock3", 400, 49.58, 55.74), ("stock4", 235, 54.21, 65.27), ("stock5", 150, 124.31, 172.45)] mydata = {} for stock in x: mydata[stock[0]] = stock[1:] # use my new dictionary for calculation headers1 = ["Stock Symbol", "No Shares", "Earnings/Loss"] headers = ["Stock Symbol", "No Shares", "Purchase Price", "Current Value"] separator1 = '+----------------+-------------+-----------------+' separator2 = '+================+=============+=================+' print("\nStock Earnings/Losses ") print(separator1) print('| {:14} | {:11} | {:15} |'.format(*headers1)) print(separator2) for key, value in mydata.items(): s = (value[3] - value[2]) * value[1] print('| {:14} | {:11} | {:16} | {:15} |'.format(key, *value), s) print(separator1)
RE: Dictionary Calculation - ichabod801 - Apr-22-2019 Deleting post content is against the rules around here. I have put the content back, please leave it that way. Even better, you could post your solution so that other's could learn from it. RE: Dictionary Calculation - prophet11 - Apr-22-2019 Oh most definitely. I agree!!! I was editing it. Thank you for the reply. I still have not solved the issue. RE: Dictionary Calculation - Yoriz - Apr-22-2019 List have a zero based index s = (value[3] - value[2]) * value[1]gives the error because value[3] is looking for the 4th item, which there is not oneremove -1 from all the index values s = (value[2] - value[1]) * value[0] |