I am not sure if I am asking the question correctly but I mean the following:
Lets say I have dictionary
p = {'A' : 1, 'B' : 2, 'C' : 3}
then I have list
q = ['A', 'B']
how do I sum q so that the result is 3?
Thanks!
I am not sure if I am asking the question correctly but I mean the following:
Lets say I have dictionary
p = {'A' : 1, 'B' : 2, 'C' : 3}
then I have list
q = ['A', 'B']
how do I sum q so that the result is 3?
Thanks!
Use the built-in function sum
and a generator expression:
>>> p = {'A' : 1, 'B' : 2, 'C' : 3}
>>> q = ['A','B']
#using generator expression
>>> sum(p.get(x,0) for x in q)
3
#using list comprehension, not memory efficient
>>> sum( [p.get(x,0) for x in q] )
3
In case any of the element in q
is not found in p
then dict.get
will return the default value 0
, so no errors will be raised.
help on dict.get
:
>>> print dict.get.__doc__
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
The list comprehension version is roughly equivalent to:
sums = []
for x in q: #loop over each item in q
sums.append(p.get(x,0)) #fetch the value of item from p and append it to sums
print sum(sums) # sum the list sums
(p.get(x,0) for x in q)
is a generator expression, instead of generating whole list in memory it returns one value at a time.
summ = 0
for x in q:
summ += p.get(x,0)
print summ
You can do
sum(p[k] for k in q)
This expression p[k] for k in q
is a generator comprehension- similar to a list comprehension except that it never has to construct the entire list (which makes it faster and more memory-efficient when all you need is the sum).
Note that this code is basically a more concise version of:
total = 0
for k in q:
total = total + p[k]
Which might be a bit clearer to you.
One way with functional programming and the operator.itemgetter function:
>>> p = {'A' : 1, 'B' : 2, 'C' : 3}
>>> q = ['A', 'B']
>>> import operator
>>> sum(operator.itemgetter(*q)(p))
3
Another approach: Take advantage of the fact that viewkeys
on the dictionary
returns a set
-like object. For large lists, this offers performance advantages.
sum(p[x] for x in p.viewkeys() & q)