2013-02-26 199 views
0

我有時間序列字典可用,我需要計算每個鍵的所有值,什麼是最有效的方法來做到這一點?列表聚合列表的Python字典

DATA = {u'604 ':[[1361836800,{u'14885549':52,u'91478624 ':127,u'25581439':12,u'532617990' :4}],[ 1361833200,{u'14885549 ':38,u'91478624':204,u'25581439 ':14,u'40302362':5,u'532617990' :2}]]}

我試圖這是在這裏(這肯定是愚蠢的,但工程):

total = 0 
for i in DATA: 
    for j in DATA[i]: 
     for k in j[1]: 
      total += j[1][k] 

請幫忙嗎?

回答

4

使用sum()與發電機:

total = sum(sum(inner[1].values()) for outer in DATA.values() for inner in outer) 

這行爲等同於for循環如下:

total = 0 
for outer in DATA.values(): 
    for inner in outer: 
     total += sum(inner[1].values())