Reputation: 91
So I have a dictionary which looks like this:
d = {1:2, 2:4, 3:6, 4:8, 5:10}
Is there a way to add together multiple values? For example I want to add together every value from 1-3 that should give me 12.
Upvotes: 0
Views: 81
Reputation: 19761
It sounds like you want to do something like:
>>> d = {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
>>> start = 1
>>> end = 3
>>> sum(d[i] for i in range(start, end + 1) if i in d)
12
This will sum the values from d
for the keys 1-3 (inclusive).
Upvotes: 4
Reputation: 5440
Try this:
d = {1:2, 2:4, 3:6, 4:8, 5:10}
total = 0
for n in range(1, 3+1):
if n in d:
total += d[n]
print(total)
Upvotes: 0