Search code examples
pythondictionaryreadfile

calculating duplicates payload from text file Python


I am trying to calculate the scores entry for people from a text file:

essi 5 pietari 9 essi 2 pietari 10 pietari 7 aps 25 essi 1

output expected:

Contestant score: aps 25 essi 8 pietari 26

my output: aps 25 essi 11 pietari 77

my code calculation is wrong!

my code is:

def reading():
"""
reads input file name and open it, split lines from text in 2.
do the calculation, print out the dictionary
:return: dict.
"""
file1 = input("Enter the name of the score file: ")
read_file = open(file1, mode="r")
dict = {}

for line in read_file:
    # Remove the character(s) that end the line.
    line = line.rstrip()

    # Split the line in two.
    name, score = line.split(" ")

    # Add a new entry to the phone book.
    if name not in dict:
        dict[name] = score

    elif name in dict:
        dict[name] = score + score

#Close the file.
read_file.close()

#print dict sorted
for p in sorted(dict.keys()):
    print(f"{p} {dict[p]}")

def main():
    #the function call
    reading()

if __name__ == "__main__":
        main()

Solution

  • Try the below. (zz.txt holds your data)

    Few points that you need to take from the code:
    @ do not name you data structure variable 'dict'
    @ use 'with' when you open files
    @ work with defaultdict when you can

    from collections import defaultdict
    
    data = defaultdict(int)
    with open('zz.txt') as f:
        lines = [l.strip() for l in f.readlines()]
        for line in lines:
            fields = line.split(' ')
            data[fields[0]] += int(fields[1])
    print(data)
    

    output

    defaultdict(<class 'int'>, {'essi': 8, 'pietari': 26, 'aps': 25})