Python Forum
RuntimeError: dictionary changed size during iteration
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
RuntimeError: dictionary changed size during iteration
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  help RuntimeError: no running event loop marpaslight 5 3,753 Oct-18-2022, 10:04 PM
Last Post: marpaslight
  The behavior of tune model has changed Led_Zeppelin 5 4,458 Oct-21-2021, 06:52 PM
Last Post: jefsummers
  bleak library RuntimeError: This event loop is already running alice93 3 4,116 Sep-30-2021, 08:06 AM
Last Post: alice93
  how can a variable change if I haven't changed it? niminim 5 3,080 Apr-07-2021, 06:57 PM
Last Post: niminim
  RuntimeError: generator raised StopIteration quest 1 5,824 Mar-28-2021, 08:11 PM
Last Post: quest
  new help with dictionary and dataframe iteration AlphFinan 0 1,531 Oct-13-2020, 11:04 PM
Last Post: AlphFinan
  RuntimeError: This event loop is already running newbie2019 2 6,963 Sep-30-2020, 06:59 PM
Last Post: forest44
  RuntimeError: Optimal parameters not found: Number of calls to function has reached m bntayfur 0 6,157 Aug-05-2020, 04:41 PM
Last Post: bntayfur
  Dictionary iteration and creation a new dictionary from duplicates xrsxlnx 2 2,141 Mar-30-2020, 10:43 AM
Last Post: xrsxlnx
  size of set vs size of dict zweb 0 2,150 Oct-11-2019, 01:32 AM
Last Post: zweb

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020