Skip to content Skip to sidebar Skip to footer

Runtimeerror: Dictionary Changed Size During Iteration

This is my code: import os import collections def make_dictionary(train_dir): emails=[os.path.join(train_dir,f) for f in os.listdir(train_dir)] all_words=[] for mail

Solution 1:

Take a look at this two code snippets:

d = {1: 1, 2: 2}
f = [x for x in d]
del d[1]
print(f)  # [1, 2]

and:

d = {1: 1, 2: 2}
f = d.keys()
del d[1]
print(f)  # dict_keys([2])

As you can see, in the first one the dictionary d and the list f are not related to one another; changes in the dict are not reflected to the list.

On the second snippet, due to the way we create the list f it remains linked to the dict so deleting elements of the dict also removes them from the list.

Both behaviors might be somewhere helpful but in your scenario it is the first one you want.

Post a Comment for "Runtimeerror: Dictionary Changed Size During Iteration"