'Python: RuntimeError: dictionary changed size during iteration

I'm working with a dict with a key and a number and some text as a tuple, like this:

self.dic = {'D': ('1', 'Dog, 2015.'), 'C': ('2', 'Cat, 2018.'), 'M': ('3', 'Mouse, 2017.')}

I'm getting the key and the text from two list, but I've to add the number manually and it need to be an unique number for every text (so I need to check that). If it is an unique number I'd like to create new key and values, but I'd also like to use the same button to update the number if a different one is in self.number_e when the button is clicked again. This is my code right now and this is the error I'm getting: RuntimeError: dictionary changed size during iteration

        self.number_e = tk.Entry(self, justify="center", width=6)
        self.number_e.pack(padx=15, ipady=5, pady=15, side="top")

        btn = tk.Button(self, text="Add", command=self.add)
        btn.pack(side="top")   

        
    def add(self):
        for key, val in self.dic.items():
            if self.number_e.get() in str(val[0]) and val[1] != text: # allow duplicate number only if text is the same, example: 'DT': ('1', 'Dog, 2015.')
                print(f"Error: Number already used for {val[1]}") # otherwise prints an error, example: 'F': ('1', 'Fish, 2012.')
            else: # if the number is not in the self.dict:
                if key in self.dic: # if the key is already saved in the self.dict then just update the number if a new one is in self.number_e.get(). The key and the text stay the same
                    self.dic[k] = (self.number_e.get(), val[1])
                else: # if the key is a new one create new key and values
                    self.dic[k] = self.number_e.get(), text

How can I fix it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source