Guilherme Londero
Guilherme Londero

Reputation: 19

RuntimeError: dictionary changed size during iteration PYTHON

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())

Upvotes: 0

Views: 998

Answers (1)

damaBeugXam
damaBeugXam

Reputation: 11

Try replacing the variable keys by the expression connecteds.keys(). I am assuming that you are using Threads and also that connecteds is being used in these threads. May be that is changing the size.

Upvotes: 1

Related Questions