Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A simple test in the console shows you cannot modify a dictionary while iterating over it:</p> <pre><code>&gt;&gt;&gt; mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4} &gt;&gt;&gt; for k, v in mydict.iteritems(): ... if k == 'two': ... del mydict[k] ... ------------------------------------------------------------ Traceback (most recent call last): File "&lt;ipython console&gt;", line 1, in &lt;module&gt; RuntimeError: dictionary changed size during iteration </code></pre> <p>As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the <code>keys()</code> method to get a list of the keys and work with that:</p> <pre><code>&gt;&gt;&gt; for k in mydict.keys(): ... if k == 'two': ... del mydict[k] ... &gt;&gt;&gt; mydict {'four': 4, 'three': 3, 'one': 1} </code></pre> <p>If you need to delete based on the items value, use the <code>items()</code> method instead:</p> <pre><code>&gt;&gt;&gt; for k, v in mydict.items(): ... if v == 3: ... del mydict[k] ... &gt;&gt;&gt; mydict {'four': 4, 'one': 1} </code></pre> <p><strong>EDIT:</strong></p> <p>Above will not work for Python3 and will give a <code>RuntimeError</code>.</p> <blockquote> <p>RuntimeError: dictionary changed size during iteration.</p> </blockquote> <p>This happens because <code>mydict.keys()</code> returns an iterator not a list. As pointed out in comments simply convert <code>mydict.keys()</code> to a list by <code>list(mydict.keys())</code> and it should work.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload