Keith
Keith

Reputation: 3

Sum values of a dictionary

I am trying to sum values for a slice of a dictionary with class int values.

Here is my code:

from scipy.stats import poisson

inventories = 4 # states
mu = 1 # value for lambda
prob = []
for i in range(inventories):
     prob.append(poisson.pmf(i, mu))

Transitions = {}
for i in range(inventories):
    for j in range(inventories-1,-1,-1):
        if i - j < 0:
            Transitions[0,i,j] = 0
        elif j <> 0:
            Transitions[0,i,j] = prob[i-j]
        elif j == 0:
            Transitions[0,i,j] = 1

If you run this I am trying to get the last line of code to sum over all j for each i. I am a MATLAB coder so I am used to matrices and I think this is screwing me up. Any help is much appreciated.

Upvotes: 0

Views: 496

Answers (1)

BenDundee
BenDundee

Reputation: 4521

You can slice the dictionary using list comprehensions:

>>> l=[v for (k,v) in Transitions.iteritems() if k[1] == 3]
>>> sum(l)
1.9196986029286058

This gives the sum over j for i = 3. To sum over i, replace k[1] with k[2].

All told, list comprehensions like this are pretty speedy, though I can't say how they rank against scipy matrices.

You can also get fancy:

>>> l=[sum([v for (k,v) in Transitions.iteritems() if k[1] == i]) for i in range(1,4,1)]
>>> l
[1.3678794411714423, 1.7357588823428847, 1.9196986029286058]

This gives you the sum over each row.


So the above is based on my misunderstanding of the question. Sorry, OP :(

I think you want to replace the line with something like:

Transitions[0,i,j] = sum([Transitions[0,i,k] for k in range(1,i+1,1)])

Upvotes: 2

Related Questions