Zac
Zac

Reputation: 372

Summing values in a dictionary based on multiple conditions

I'm trying to sum values between multiple dictionaries, for example:

oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2}
otherDic = {'A': 9, 'D': 1, 'E': 15}

I want to sum up the values of in oneDic if they are found in otherDic and if the corresponding value in otherDic is less than a specific value

oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2}
otherDic = {'A': 9, 'D': 1, 'E': 15}
value = 12
test = sum(oneDic[value] for key, value in oneDic.items() if count in otherTest[count] < value
return (test)

I would expect a value of 4, because C is not found in otherDic and the value of E in otherDic is not less than value

But when I run this code I get a lovely key error, can anybody point me in the right direction?

Upvotes: 1

Views: 800

Answers (2)

sshashank124
sshashank124

Reputation: 32189

The following code snippet works. I do not know what the count variable in your code is:

oneDic = {'A': 3, 'B': 0, 'C':1, 'D': 1, 'E': 2}
otherDic = {'A': 9, 'D': 1, 'E': 15}

value = 12
test = sum(j for i,j in oneDic.items() if (i in otherDic) and (otherDic[i] < value))
print(test)

Link to working code

Upvotes: 1

sberry
sberry

Reputation: 132018

How about this

sum(v for k, v in oneDic.items() if otherDic.get(k, value) < value)

Here we iterative over the k, v pairs of oneDic and only include them if the return from otherDic.get(k, value) is < value. dict.get takes two arguments, the second being optional. If the key is not found, the default value is used. Here we set the default value to be value so that missing keys from otherDic are not included.

By the way, the reason you get the KeyError is because you are trying to access B and C at some point in the iteration by doing otherDic['B'] and otherDic['C'] and that is a KeyError. However, using .get as in otherDic.get('B') will return the default of None since you did not supply a default - but it will not have a KeyError

Upvotes: 1

Related Questions