I'm trying to remove a key-value from a dictionary by a condition, but when i try i recive the error
RuntimeError: dictionary changed size during iteration
Here is my code
threading.Timer(5.0, compare_time_connecteds).start()
FMT = '%H:%M:%S'
datesys_compare = datetime.now().strftime("%H:%M:%S")
keys = connecteds.keys()
if len(keys) != 0:
for i in keys:
true_time = datetime.strptime(datesys_compare, FMT) - datetime.strptime(connecteds.get(i), FMT)
difference_in_seconds = true_time.total_seconds() #
if difference_in_seconds > 20:
connecteds.pop(i)
And here is the error
for i in keys:
RuntimeError: dictionary changed size during iteration
I solved this forcing the keys to be a list
FMT = '%H:%M:%S'
datesys_compare = datetime.now().strftime("%H:%M:%S")
keys = list(connecteds.keys())
dictionarywhile looping it is problematic. Try adding keys and values to an emptydictunlessdifference_in_seconds > 20keys = list(connecteds.keys()). This happens because the keys object you are iterating over is taking values from the respective dictionary in "real time" and not a static list.