Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to sum new value to existing one? [closed]

Tags:

python

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'}

like image 899
MT247 Avatar asked Oct 17 '25 06:10

MT247


2 Answers

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.

like image 120
Abhinav Mathur Avatar answered Oct 18 '25 18:10

Abhinav Mathur


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])
like image 33
wagnifico Avatar answered Oct 18 '25 20:10

wagnifico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!