循环遍历多维字典并计算

时间:2017-06-14 18:32:34

标签: python for-loop

对此必须有疑问,但我无法找到。

我有这样的字典:

data = {
    "Jan": {
        "2017-01-01 00:00:00": {
            "001": 10,
            "002": 20,
            "003": 30
        },
        "2017-01-01 01:00:00": {
            "001": 20,
            "002": 40,
            "003": 50
        },
        "2017-01-01 02:00:00": {
            "001": 90,
            "002": 50,
            "003": 60
        }
    }
}

我想遍历字典并计算累积点,如果可能的话改变字典。例如,对于001,它将是

data["Jan"]["2017-01-01 00:00:00"]["001"] == 10
data["Jan"]["2017-01-01 01:00:00"]["001"] == 30
data["Jan"]["2017-01-01 02:00:00"]["001"] == 120

我不想得到最终的累积金额,我想要亲戚。

现在我有了这段代码:

import copy
from datetime import datetime, timedelta

copydata = copy.deepcopy(data)
# I made a copy because I have an if statement and Python was
  complaining that the dictionary changed size during iteration

for i, month in enumerate(copydata):
    for dt in copydata[month]:
        for user in copydata[month][dt]:
            current_datetime = datetime.strptime(dt, '%Y-%m-%d %H:00:00')
            cumulativepoints=data[month][dt][user] # getting the current hour's points. Since the loop is in random order, it can start at any time
            if current_datetime.hour > 0: # if the hour is 0 then it's the first hour and I don't need to calculate anything
                for x in range(1, current_datetime.hour+1): # starting at 01:00:00 till the current_datetime.hour plus one to count itself
                    past_time = current_datetime - timedelta(hours=x)
                    past_time = past_time.strftime('%Y-%m-%d %H:00:00')
                    if data[month][past_time]:
                        cumulativepoints += data[month][past_time][user]
                    data[month][past_time][user] = cumulativepoints # <--- the error happens here

但在该行data[month][past_time][user] = cumulativepoints,Python会抛出错误:TypeError: list indices must be integers, not str

我很确定这段代码比它应该复杂得多。但由于许多错误信息,这是许多改编的结果。

1 个答案:

答案 0 :(得分:1)

  

问题:循环遍历多维字典并计算

你可以这样做,例如:

def pp_dict():
    for month in data:
        print('month:{}'.format(month))
        for dt in sorted(data[month]):
            print('\tdt:{}'.format(dt))
            for user in sorted(data[month][dt]):
                print('\t\tuser:{}:{}'.format(user, data[month][dt][user]))

def cum_sum(month, user):
    cum_sum = 0
    for dt in sorted(data[month]):
        cum_sum += data[month][dt][user]
        data[month][dt][user] = cum_sum


for user in ['001']:
    cum_sum('Jan', user)

pp_dict()
  

输出

month:Jan
dt:2017-01-01 00:00:00
    user:001:10
    user:002:20
    user:003:30
dt:2017-01-01 01:00:00
    user:001:30
    user:002:40
    user:003:50
dt:2017-01-01 02:00:00
    user:001:120
    user:002:50
    user:003:60

使用Python测试:3.4.2