如何基于星期过滤datatime对象字典

时间:2018-07-17 08:54:01

标签: python dictionary

因此,我从fitbit API中提取了数据,并以以下格式获取了字典:

weightData = {'January': {datetime.date(2018, 1, 1): {'weight': 0, 'fat': 0}, datetime.date(2018, 1, 2): {'weight': 0, 'fat': 0}

现在,我想计算每周的平均值。我搜索了谷歌,发现datetime.isocalendar()方法。效果很好,但我不知道如何遍历字典。这是我的尝试:

for i in range (1, 30):
for month in data:
    for date in data[month]:
        if date.isocalendar()[1] == i:
            tmpWeight += data[month][date]["weight"]
            tmpFat += data[month][date]["fat"]
            counter += 1
        elif date.isocalendar()[1] > i:
            continue
avgWeight.append(tmpWeight/counter)
avgFat.append(tmpFat/counter)
tmpWeight = 0
tmpFat = 0
counter = 0

但是我收到“ ZeroDivisionError:被零除”。我假设发生在date.isocalendar()[1]!= i时,它会尝试将某些值除以值为0的“计数器”。

有人可以指出我的错误吗?

1 个答案:

答案 0 :(得分:0)

我认为您可以按照以下方式解决您的问题:

import datetime

data = {
    'January': {
        datetime.date(2018, 1, 1): {'weight': 1, 'fat': 30}, 
        datetime.date(2018, 1, 2): {'weight': 15, 'fat': 300}
    }
}

result = dict()

for month in data.keys():
    for date in data[month].keys():

        week_number  = date.isocalendar()[1]

        if week_number not in result.keys():
            result[week_number] = {
                "weight": 0,
                "fat": 0,
                "counter": 0
            }                

        result[week_number]["weight"] += data[month][date]["weight"]
        result[week_number]["fat"] += data[month][date]["fat"]
        result[week_number]["counter"] += 1

for week_number in result.keys():  
    result[week_number] = {
        "weight": result[week_number]["weight"] / result[week_number]["counter"],
        "fat": result[week_number]["fat"] / result[week_number]["counter"]
    }

print(result)

它给您:

{1: {'weight': 8.0, 'fat': 165.0}}

您提出的代码效率很低,原因如下:

  • 从1到30的循环是没有用的
  • 不需要温度值
  • 不需要平均值
  • 在划分不必要的复杂算法之前,您没有检查计数器是否为!= 0