By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,923 Members | 1,443 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,923 IT Pros & Developers. It's quick & easy.

In a dictionary, sum values if similar keys

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

Date: 12.12
Scores: 2

Date: 9.12
Scores: 4

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:

Expand|Select|Wrap|Line Numbers
  1. if ID is not None:
  2.     if ID not in scoreDict:
  3.         scoreDict[ID] = set()
  4.     scoreDict[ID].add(Scores)
  5.     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
Dec 21 '10 #1
Share this Question
Share on Google+
4 Replies

Expert 100+
P: 624
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.
Expand|Select|Wrap|Line Numbers
  1. if ID not in scoreDict:
  2.     scoreDict[ID] = 0
  3. scoreDict[ID] += score 
Dec 22 '10 #2

P: 22
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:
Expand|Select|Wrap|Line Numbers
  1. scoreDict.setdefault(ID, 0)
  2. scoreDict[ID] += int(score)
thanks a lot again,
Dec 22 '10 #3

Expert Mod 10K+
P: 12,383
Because score probably isn't defined. From your original code, it looks like you have a variable called scores but not score.
Dec 22 '10 #4

Expert 100+
P: 624
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.
Dec 22 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.