简体   繁体   中英

How can I add the values of the same key to one another from a file within a dictionary?

My text file looks like so (Number of goals each person scores at different dates):

1/23/15 Jack G2
3/15/15 Sally G5
1/23/12 Jack G1
3/15/14 Sally G3

What I want to do is turn that file into a dictionary, I have done:

Goal = {}
with open("(goals_per_person.txt") as goal:
    for line in bill:
        (name,score) = line.split()
        Goals_per_person[int(name)] = goals

But I'm not sure, how I can ignore the date because it's not needed. After I get the respective goal per person i want to add that onto each other and print it. So add the values of the same key

A simple solution is to just disregard the first column of the split, throwing the value into a dummy variable

dummy, name, score = line.split()

Instead of dummy , a common convention is to use _ as the variable, or use that as a prefix ( _dummy ) to indicate you won't use it.

As an FYI, you will run into the other problems

  • name is not an integer
  • Goals_per_person should be Goal
  • You want to put score into the dictionary, not goals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM