Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to change dictionary keys from strings to integers and get this error: RuntimeError: dictionary keys changed during iteration

def load_method(self, inp_list, file):
       self.DB.global_row = -1
       # clear the widgets and listbox
       self.DB.clear_test_list()
       for item in self.DB.inp_dict:
           del item
       inp_list.delete(0, 'end')
        # THIS IS THE RELEVANT PART FOR THIS QUESTION
       [self.DB.test_dict, self.DB.inp_dict] = json.load(file)
       counter = 0
       for key in self.DB.test_dict:                       # change the keys to be integer instead of strings
           self.DB.test_dict[counter] = self.DB.test_dict[key]
           del self.DB.test_dict[key]
           counter += 1

I’m sure there is a correct way to do it, does anyone know how?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’d have to create a new dictionary from your existing one. A simple pythonic way of achieving this would be by changing the code as follows:

def load_method(self, inp_list, file):
    self.DB.global_row = -1
    # clear the widgets and listbox
    self.DB.clear_test_list()
    for item in self.DB.inp_dict:
        del item
    inp_list.delete(0, 'end')
    # THIS IS THE RELEVANT PART FOR THIS QUESTION

    [self.DB.test_dict, self.DB.inp_dict] = json.load(file)
    self.DB.test_dict = {int(idx): self.DB.test_dict[key] for idx, key in enumerate(d.keys())}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading