python字典datetime作为键,keyError [英] python dictionary datetime as key, keyError

查看:1415
本文介绍了python字典datetime作为键,keyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Linux中使用cron运行Python脚本,这应该构造一个数据字典.我正在尝试使用datetime().now().time()作为字典中的键,但似乎会引发错误.

datetime类型不能用作Python中的字典键吗?如果是这样,我有什么选择?

代码:

time_now = dt.datetime.now().time()
date_today = dt.datetime.now().date()
usage_dict_hourly = {}
date_wise_dict = {}

def constructing_dict(data_int):
    date_wise_dict[usage_dict_hourly[time_now]] = data_int
    print date_wise_dict

错误:

<ipython-input-9-ef6a500cc71b> in constructing_dict(data_int)
     36 
     37 def constructing_dict(data_int):
---> 38     date_wise_dict[usage_dict_hourly[time_now]] = data_int
     39     print date_wise_dict
     40 

KeyError: datetime.time(22, 40, 33, 746509)

解决方案

回答有关日期时间的问题作为字典键:

是的,可以将datetime的时间对象用作字典键.

使用对象作为字典键的条件:

要用作字典键,对象必须支持哈希函数(例如,通过__hash__),相等性比较(例如,通过__eq____cmp__)(...)

(来源:字典键)

引用时间对日期时间的支持:

支持的操作:

...

  • 哈希,用作字典键

(来源: datetime-时间对象)

但是,由于dict usage_dict_hourly为空,因此您将收到此异常.

usage_dict_hourly{}启动.因此,当您尝试在函数constructing_dict中查找键为time_now的元素时,它会引发KeyError异常,因为尚未找到该键.

I'm trying to run a Python script using cron in Linux, which should construct a dictionary of data. I'm attempting to use datetime().now().time()as keys in the dictionary, but it seems to raise an error.

Can't the datetime type be used as a dictionary key in Python? If that is the case, what are my alternatives?

Code:

time_now = dt.datetime.now().time()
date_today = dt.datetime.now().date()
usage_dict_hourly = {}
date_wise_dict = {}

def constructing_dict(data_int):
    date_wise_dict[usage_dict_hourly[time_now]] = data_int
    print date_wise_dict

Error:

<ipython-input-9-ef6a500cc71b> in constructing_dict(data_int)
     36 
     37 def constructing_dict(data_int):
---> 38     date_wise_dict[usage_dict_hourly[time_now]] = data_int
     39     print date_wise_dict
     40 

KeyError: datetime.time(22, 40, 33, 746509)

解决方案

Answering your question about datetime as a dictionary key:

Yes, time object of datetime can be used as dictionary key.

Conditions to use an object as a dictionary key:

To be used as a dictionary key, an object must support the hash function (e.g. through __hash__), equality comparison (e.g. through __eq__ or __cmp__)(...)

(Source: DictionaryKeys)

datetime support for cited conditions:

Supported operations:

...

  • hash, use as dict key

(Source: datetime - time Objects)

However, you are getting this exception because dict usage_dict_hourly is empty.

usage_dict_hourly is initiated with {}. So, when you try to look for the element with key time_now in your function constructing_dict, it raises KeyError exception, because that key has not been found.

这篇关于python字典datetime作为键,keyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆