title: Iterating through and mutating dictionary
body: <p>I am running into issues iterating through, and modifying, a dictionary...</p>
  <p>Say I have a dictionary:</p>
  <pre><code>dict1 = {'A' : 'first', 'B' : 'second', 'C' : 'third', 'D' : 'fourth'}
  </code></pre>
  <p>I want to iterate through dict1, using the data within to build up a second dictionary. Once finished with each entry in <code>dict1</code>, I delete it.</p>
  <p>In pseudocode:</p>
  <pre><code>dict2 = {}
  
  for an entry in dict1:
      if key is A or B:
          dict2[key] = dict1[key]   # copy the dictionary entry
      if key is C:
          do this...
      otherwise:
          do something else...
      del dict1[key]
  </code></pre>
  <p>I know that altering the length of an iterable in a loop causes problems and the above may not be simple to achieve.</p>
  <p>The answer to this question to <a href="https://stackoverflow.com/questions/3616721/iterating-over-dictionary-items-values-keys-in-python-3">this question</a> seems to indicate that I can use the <code>keys()</code> function as it returns a dynamic object. I've thus tried:</p>
  <pre><code>for k in dict1.keys():
      if k == A or k == B:
          dict2[k] = dict1[k]
      elif k == C:
          dothis()
      else:
          dosomethingelse()
      del dict1[k]
  </code></pre>
  <p>But, this simply gives:</p>
  <blockquote>
  <p>'RuntimeError: dictionary changed size during iteration'</p>
  </blockquote>
  <p>after the first deletion. I have also tried using <code>iter(dict1.keys())</code> but got the same error.</p>
  <p>I'm thus a little confused and could do with some advice. Thanks</p>