累积orderedDict

时间:2013-12-04 21:06:20

标签: python python-2.7 ordereddictionary

这就是我的想法:我有一个如此简化的orderedDict:

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

我想做的是通过某种方式迭代积累所有积累的值。 E.G.,我希望最终结果与此相似(基于上面的例子)

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

我正在思考这些问题,但显然需要一种方法来确定以前的密钥。

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

我认为这不是坏习惯,因为orderedDict暗示它维持秩序所以它应该是稳定的,不是吗? 我该怎么做呢?

谢谢

1 个答案:

答案 0 :(得分:4)

跟踪总数:

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

订购不会受到影响;只有键会添加到订购中。

演示:

>>> 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)])