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)
You aren't actually setting
useage_dict_hourly
to any value that way, that's your error. You should ideally do something like:Or, better yet, just use datetime.datetime.now() as the key:
This way, there is no possibility of clashes in the value (which is possible - though unlikely - for useage_dict_hourly)
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:
(Source: DictionaryKeys)
datetime support for cited conditions:
(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 keytime_now
in your functionconstructing_dict
, it raisesKeyError
exception, because that key has not been found.