0

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())
3
  • Size changing your dictionary while looping it is problematic. Try adding keys and values to an empty dict unless difference_in_seconds > 20 Commented Apr 6, 2022 at 20:00
  • Just force the keys to be a list and not keys object, to do so: keys = 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. Commented Apr 6, 2022 at 20:01
  • @Elger thanks so much for your help! This list solve my problem! Commented Apr 6, 2022 at 20:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.