Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary Calculation
#1
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 | +================+=============+=================+
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Oh most definitely. I agree!!!

I was editing it. Thank you for the reply. I still have not solved the issue.
Reply
#4
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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Calculation Inside Dictionary Error prophet11 3 2,594 Apr-22-2019, 05:23 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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