Search code examples
pythonfileprintingline

python printing total result from file by only printing every name once?


Hi I'm trying to print some information from a file to get the names of the person only to show up once with all the numbers of the person added together.

The information from the file looks something like this: randomfile.txt

Jack, 20.00
Sofie, 12.00 
Jack, 32.50
Sofie, 33.75

The output I want:

Jack   52.50
Sofie  45.75

I know how to get all the information but I don't know how to get the information added up so that I can print it without having to print the names multiple times.


Solution

  • Simple approach.

    scores = {}
    for line in txtfile:
        name, score = line.split(",")
        if name in scores:
             scores[name] += score
        else:
             scores[name] = score
    for k,v in scores.items():
       print(k,v)
    

    You still have some tweaks to do here... I'll leave those to you