Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply keys*values in a dict?

Tags:

python

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
like image 813
Chris Avatar asked Jan 16 '23 12:01

Chris


1 Answers

This way:

sum(k*v for k,v in a.items())

or with semantic naming:

sum(p*c for p,c in primesToCounts.items())
like image 195
ninjagecko Avatar answered Jan 30 '23 04:01

ninjagecko