Reputation: 141
There doesnt seem to be a good answer for this that I could find on SO, so here is my question:
I have a dictionary that I performed some math on:
for key in categoryStore:
finalScoreStore[key] = (categoryStore[key] / totalStore[key]) * weightStore[key]
This ends up leaving me with a dictionary with a large number in it. I am trying to get it down to 2 decimal places:
{'Exercise': 2.6624999999999996, 'Assignment': 9.333333333333334, 'Project': 13.770000000000001, 'Quiz': 18.4375, 'Exam': 29.88, 'Finals': 8.64}
I have tried to do a :.2f with a print statement, but I am getting an error probably because it is trying to format the keys and the values. So, I'm not sure how to go about formatting all values to 2 decimal places. I'm thinking it would have to be done either in or directly after the first code block above.
I appreciate any help!
Upvotes: 1
Views: 3152
Reputation: 16633
If you want a float, change your loop to:
for key in categoryStore:
finalScoreStore[key] = round((categoryStore[key] / totalStore[key]) * weightStore[key], 2)
If you want a string:
for key in categoryStore:
finalScoreStore[key] = '{:.2f}'.format((categoryStore[key] / totalStore[key]) * weightStore[key])
Upvotes: 2