Stacks of overflow
Stacks of overflow

Reputation: 87

Dictionary changes size during iteration

I looked through the database of answers pertaining to this topic and couldn't find an answer, essentially I'm looping through a dictionary, I'm getting the, "dictionary changes size," runtime error yet I'm popping out one key and value and inserting another before the iteration resumes.

       for patterns in dict_copy.keys():
            new_tuple = ()
            for items in range(len(patterns)):
                if patters[items] not in exclusion:
                    new_tuple += (patterns[items],)
            dict_copy[new_tuple] = dict_copy.get(patterns)
            dict_copy.pop(patterns)

The dictionaries I'm working with are in the form: {("A","B","C","D"):4, ("B","A","C","D") "2...} I'm pretty much just confused over the fact that it thinks I'm chaning the dictionary size

Upvotes: 1

Views: 1260

Answers (2)

Gil
Gil

Reputation: 952

I'm popping out one key and value and inserting another before the iteration resumes.

That does not matter. You cannot change a data structure while iterating it. Python's iterator gets confused (-: It's not about the size of the dictionary, but its content. (It's the same way in other programming languages too...)

Upvotes: 1

NPE
NPE

Reputation: 500307

The error is slightly misleading. What it's trying to tell you is that you're not supposed to make any structural changes (insertions/deletions) while iterating over the dict.

An easy way to fix this is by placing the result into a separate dictionary:

   new_dict = {}
   for patterns in dict_copy.keys():
        new_tuple = ()
        for items in range(len(patterns)):
            if patters[items] not in exclusion:
                new_tuple += (patterns[items],)
        new_dict[new_tuple] = dict_copy.get(patterns)
   dict_copy = new_dict

Upvotes: 1

Related Questions