KeyError
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&apos...