1

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!

user2444127
  • 53
  • 1
  • 4
  • 3
    This is a fairly simple task; you should be able to do this if you know how to use a dictionary and how to loop over the elements of a list... – Rushy Panchal Jun 01 '13 at 22:43

4 Answers4

6

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Sorry, Im a bit new to Python, can you explain what is happening? and thanks for the quick response! – user2444127 Jun 01 '13 at 22:23
  • Thank you! now just one more quick question which I should have added in the main question, if you can answer it (sorry!) my list actually has a pair of values ex: Pair1 = ("A", "B", "C") Dict = {"E" : 1, "F" : 2, "G" : 3) mylist = [AE, BF] I want to sum the E and F solely to get 3 – user2444127 Jun 01 '13 at 22:38
  • 2
    @user2444127 Don't move the goalposts on existing questions. While your new question is related, it's still a new problem, belongs in a separate question, and you should try working it out on your own first. – millimoose Jun 01 '13 at 22:41
  • @user2444127 try something like : `sum(Dict.get(x[1],0) for x in mylist)` – Ashwini Chaudhary Jun 01 '13 at 22:43
4

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.

Community
  • 1
  • 1
David Robinson
  • 77,383
  • 16
  • 167
  • 187
3

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
jterrace
  • 64,866
  • 22
  • 157
  • 202
2

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)
iruvar
  • 22,736
  • 7
  • 53
  • 82