accumulating an orderedDict

140 views Asked by At

here's the idea: I have an orderedDict like so (simplified):

{'012013': 3, '022013': 1, '032013': 5}

what I want to do is make all the values accumulated by somehow iterating through it. E.G., I want the final result to resemble this (based on the above example)

{'012013': 3, '022013': 4, '032013': 9}

I was thinking something along these lines but clearly there'd need to be a way to determine previous keys.

for key, value in month_dictionary.iteritems():
   month_dictionary[key] = month_dictionary[key] + month_dictionary[previous_key]

I assume this isn't bad practice because orderedDict implies that it maintains order so it should be stable, no? How would I go about doing this?

thank you

1

There are 1 answers

0
Martijn Pieters On BEST ANSWER

Track a total:

total = 0
for key, value in month_dictionary.iteritems():
    total += value
    month_dictionary[key] = total

Ordering won't be affected; only new keys would add to the ordering.

Demo:

>>> from collections import OrderedDict
>>> month_dictionary = OrderedDict((('012013', 3), ('022013', 1), ('032013', 5)))
>>> total = 0
>>> for key, value in month_dictionary.iteritems():
...     total += value
...     month_dictionary[key] = total
... 
>>> month_dictionary
OrderedDict([('012013', 3), ('022013', 4), ('032013', 9)])