In a dictionary, sum values if similar keys

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Atrisa
    New Member
    • Sep 2010
    • 22

    #1

    In a dictionary, sum values if similar keys

    Hi everyone. I have a file of records like this:

    ID:13
    Date: 12.12
    Scores: 2

    ID:22
    Date: 9.12
    Scores: 4

    ID:13
    Date: 18.12
    Scores: 4

    I want to have the unique IDs as keys and the sum of the socres for that ID as values in the scoreDict dictionary. This is my code so far:

    Code:
    if ID is not None:
        if ID not in scoreDict:
            scoreDict[ID] = set()
        scoreDict[ID].add(Scores)
        ID = None
    I want to have for example for person with ID 13 a sum of all her goals. How do I do the summation inside that piece of code? Any guide or help is appreciated.

    Best regards, Atrisa
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    All that is required is an integer that holds the total. Also, you do not need
    if ID is not None:
    as long as "None" is not in the dictionary.
    Code:
    if ID not in scoreDict:
        scoreDict[ID] = 0
    scoreDict[ID] += score

    Comment

    • Atrisa
      New Member
      • Sep 2010
      • 22

      #3
      Thanks dwblas. For some reason it kept telling me that score is not defined, though it is. After making some changes, now the working code looks like this:
      Code:
      scoreDict.setdefault(ID, 0)
      scoreDict[ID] += int(score)
      thanks a lot again,
      Atrisa

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        Because score probably isn't defined. From your original code, it looks like you have a variable called scores but not score.

        Comment

        • dwblas
          Recognized Expert Contributor
          • May 2008
          • 626

          #5
          If you want to keep the individual scores in the dictionary in some future program, use a list instead of a set. A set does not allow duplicate entries, so if you have 2 scores that are the same for any key, only one will be in the set.

          Comment

          Working...