无法将对象保存到字典中

时间:2016-07-23 15:09:34

标签: python python-2.7 dictionary defaultdict

我试图分析发送到餐馆的在线订单的任何给定2个阶段之间的时差。以下是我尝试做的事情的概述:

  • 遍历字典对象列表
  • 将两个日期时间值之差取为总秒数
  • 将该差异保存到另一个字典,使用订单标识符作为键,将总秒差值作为值

以下是我正在迭代的列表中的示例对象(all_order_status_sorted [0]):

(772101,
[{'Accepted in Restaurant': datetime.datetime(2016, 7, 20, 18, 35, 27),
'Created': datetime.datetime(2016, 7, 20, 18, 34, 45),
'In Kitchen': datetime.datetime(2016, 7, 20, 18, 35, 31),
'Paid - Not Sent': datetime.datetime(2016, 7, 20, 18, 34, 45),
'Sent to Central POS': datetime.datetime(2016, 7, 20, 18, 34, 48),
'billId': 772101}])

这是我为在任意两个阶段之间获取差异数据而编写的函数:

def time_between_status(fromstatus, tostatus):

    summed_data = {}

    for order in all_order_status_sorted.items():
        key = order[0]
        order = order[1]
        for data in order:
            time_between = (data[tostatus] - data[fromstatus]).total_seconds()
            #print key, time_between
            summed_data.update({key : time_between})
    return summed_data

当我打印要保存在summed_data字典中的数据时(参见time_between函数中的注释行),我可以看到我要保存的所有数据。但是我一直收到以下错误:

time_between_status('Created', 'Accepted in Restaurant')

KeyError                                  Traceback (most recent call last)
<ipython-input-231-4e2d16e87842> in <module>()
     16     return summed_data
     17
---> 18 time_between_status('Created', 'Accepted in Restaurant')
     19 print summed_data

<ipython-input-231-4e2d16e87842> in time_between_status(fromstatus, tostatus)
      8         order = order[1]
      9         for data in order:
---> 10             time_between = (data[tostatus] - data[fromstatus]).total_seconds()
     11             print key, time_between
     12             summed_data.update({key : time_between})

KeyError: 'Accepted in Restaurant'

它一直指向函数的第二个参数,我无法弄清楚它为什么不保存到summed_data字典,即使它成功打印了这些数据。我错过了什么?

0 个答案:

没有答案