freshman_2021
freshman_2021

Reputation: 371

Sum values in a dictionary based on condition that matches on keys in Python

Given a dictionary:

dic = {1: 45, 2: 4, 3: 56, 4: 667, 5: 90}

I would like to sum the values if their corresponding keys are greater than or equal to a threshold (say 3) and divide the sum by a number (say 100)

I tried the following:

threshold = 3
num_to_be_divided = 100
s = sum(v for v in dic.values() if dic.keys() > threshold)
prob = s / num_to_be_divided

Upvotes: 0

Views: 1366

Answers (2)

S.B
S.B

Reputation: 16496

try this :

print(sum(value for key, value in dic.items() if key >= threshold) / num_to_be_divided)

Upvotes: 1

balderman
balderman

Reputation: 23815

Sum values in a dictionary based on condition that match keys in Python

dic = {1: 45, 2: 4, 3: 56, 4: 667, 5: 90}
X = 3
_sum = sum(v for k,v in dic.items() if k >X)
print(_sum/100)

Upvotes: 2

Related Questions