Text file contains:
Matt 25
Matt 22
John 1
John 2
John 5
And I'm trying to calculate their total points with this but now it just adds the number to value and doesn't sum it:
filename = input("Enter the name of the score file: ")
file = open(filename, mode="r")
print("Contestant score:")
score = dict()
for file_line in sorted(file):
file_line = file_line.split()
if file_line[0] in score:
score[file_line[0]] += file_line[1]
else:
score[file_line[0]] = file_line[1]
print(score)
file.close()
But print is : {'Matt': '2525', 'John': '125'}
instead of: {'Matt': '50', 'John': '8'}
Change it to
if file_line[0] in score:
score[file_line[0]] += int(file_line[1])
else:
score[file_line[0]] = int(file_line[1])
file_line[1]
is a string, so using the +=
operator just appends to the string instead of performing mathematic addition.
The problem is that you are doing the operation with strings and not integers, so you are concatenating them instead of adding the values they represent. To fix that add a call to int in both conditions:
score[file_line[0]] = int(file_line[1])
and:
score[file_line[0]] += int(file_line[1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With