KeyError
is a result of referring to a key in a dictionary that does not exist. In the following example code, we have a series of timestamps we will try to convert. One of those timestamps, 1673165179242, is too large and will generate ValueError
. When this happens, the key, which in this case, would be named timestamp2
, does not exist and will cause KeyError
when requested from the dictionary:
>>> import datetime >>> timestamps = [1363424592, 1440356096, 1673165179242] >>> def convertTime(time_list): ... data_dict = {} ... for i, value in enumerate(time_list): ... try: ... data_dict['timestamp' + str(i)] = datetime.datetime.fromtimestamp(value) ... except ValueError: ... pass ... return data_dict ... >>> converted_time = convertTime(timestamps) >>> print converted_time['timestamp0'] 2013-03-16 05:03:12 >>> print converted_time['timestamp2'] Traceback (most recent call last): File "stdin", line 1, in <module> KeyError: 'timestamp2'
One way to solve this issue would be to either check whether the key exists before printing using the dictionary has_key()
method or accounting for such a scenario in the except
block. See the following code:
>>> import datetime >>> timestamps = [1363424592, 1440356096, 1673165179242] >>> def convertTime(time_list): ... data_dict = {} ... for i, value in enumerate(time_list): ... try: ... data_dict['timestamp' + str(i)] = datetime.datetime.fromtimestamp(value) ... except ValueError: ... data_dict['timestamp' + str(i)] = '0' ... return data_dict ... >>> converted_time = convertTime(timestamps) >>> print converted_time['timestamp0'] 2013-03-16 05:03:12 >>> print converted_time['times tamp1'] 0