a = {2: 4, 3: 2, 5: 1, 7: 1}
The keys represent prime numbers; the values represent counters. I want to calculate the number you get by iterating through the dictionary keys*values and summing the total. What is the most Pythonic way to do this?
>>> [k*v for k,v in a.items()]
[8, 6, 5, 7]
but
>>> sum(k*v for k,v in a.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
This way:
sum(k*v for k,v in a.items())
or with semantic naming:
sum(p*c for p,c in primesToCounts.items())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With