How do I remove entries within a Counter object with a loop without invoking a RuntimeError?

Louis93 picture Louis93 · Aug 23, 2011 · Viewed 22.2k times · Source
from collections import *
ignore = ['the','a','if','in','it','of','or']
ArtofWarCounter = Counter(ArtofWarLIST)
for word in ArtofWarCounter:
    if word in ignore:
        del ArtofWarCounter[word]

ArtofWarCounter is a Counter object containing all the words from the Art of War. I'm trying to have words in ignore deleted from the ArtofWarCounter.

Traceback:

  File "<pyshell#10>", line 1, in <module>
    for word in ArtofWarCounter:
RuntimeError: dictionary changed size during iteration

Answer

Jochen Ritzel picture Jochen Ritzel · Aug 23, 2011

Don't loop over all words of a dict to find a entry, dicts are much better at lookups.

You loop over the ignore list and remove the entries that exist:

ignore = ['the','a','if','in','it','of','or']
for word in ignore:
    if word in ArtofWarCounter:
        del ArtofWarCounter[word]