Python Forum

Full Version: RuntimeError: dictionary changed size during iteration
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am getting RuntimeError: dictionary changed size during iteration during an iteration of a dictionary to which i am adding new entries. what i am doing is, for each key that has a '_' i am adding another key where each '_' has been replaced with '-'. the existing key is not removed. what is the suggested (pythonic) way around this? the first thought was to assign all the keys to a variable, and iterate that list (or tuple). but that didn't work (got the same error).

    ks = options.keys()
    for optkey in ks:
        if '_' in optkey:
            options[optkey.replace('_','')] = options[optkey]
            options[optkey.replace('_','-')] = options[optkey]
but ... it is iterating over ks, not the dictionary. so how does it come up with this?
Because dict.keys() doesn't return a list. It returns a view, that updates as the keys change. For this use, I'd suggest doing ks = list(options.keys()) to force a list.

>>> x = {"a":1,"b":2}
>>> keys = x.keys()
>>> keys
dict_keys(['a', 'b'])
>>> x["c"] = 3
>>> keys
dict_keys(['a', 'b', 'c'])
>>> list(keys)
['a', 'b', 'c']