Python Forum

Full Version: Dictionary Calculation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
Output:
Traceback (most recent call last): File "<input>", line 26, in <module> IndexError: tuple index out of range Stock Earnings/Losses +----------------+-------------+-----------------+ | Stock Symbol | No Shares | Earnings/Loss | +================+=============+=================+
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.
Oh most definitely. I agree!!!

I was editing it. Thank you for the reply. I still have not solved the issue.
List have a zero based index
s = (value[3] - value[2]) * value[1]
gives the error
Error:
IndexError: tuple index out of range
because value[3] is looking for the 4th item, which there is not one
remove -1 from all the index values
s = (value[2] - value[1]) * value[0]