title: RuntimeError : dictionary changed size during iteration with defaultdict()
body: <p>In the code I wrote, an error called <strong>RuntimeError: dictionary changed size during iteration</strong> occurred in the <strong>for i in graph</strong> part. although I did not change the graph dictionary at all.  I experimented with this as well as if it wasn't possible to use defaultdict in the for statement, but it worked well, the code I experimented is also attached, so can I know why this error came out?</p>
  <pre><code>def canFinish(numCourses: int, prerequisites:[[]]) -&gt; bool:
          
          graph = collections.defaultdict(list)
          visited = set()
          
          for i in prerequisites:
              graph[i[0]].append(i[1])
          
          def _dfs(i):
              if i in visited:
                  return False
              
              visited.add(i)
              for e in graph[i]:
                  if not _dfs(e):
                      return False
              visited.remove(i)
              return True
              
          
          
          for i in graph:
              if not _dfs(i):
                  return False
              
          return True
  </code></pre>
  <pre><code>---------------------------------------------------------------------------
  ---------------------------------------------------------------------------
  RuntimeError                              Traceback (most recent call last)
  &lt;ipython-input-37-33d660346b1a&gt; in &lt;module&gt;
  ----&gt; 1 canFinish(3, [[0,1],[0,2],[1,2]])
  
  &lt;ipython-input-36-fd2cb0d8dafb&gt; in canFinish(numCourses, prerequisites)
       20 
       21 
  ---&gt; 22         for i in graph:
       23             if not _dfs(i):
       24                 return False
  
  RuntimeError: dictionary changed size during iteration
  
  
  </code></pre>
  <p>experiment code</p>
  <pre><code>a = defaultdict(list)
  a[1] = [3,4,5]
  a[2]
  for q in a:
      print(q)
  
  &quot;&quot;&quot;
  OUTPUT : 1,2
  &quot;&quot;&quot;
  </code></pre>