Application of Removing Items from Dictionaries
<p>Suppose I have a dictionary that contains instances of kinematic objects. Each kinematic object has a position, velocity, etc. On each timestep update for the program, I want to check to see if two active objects (not the same object, mind you) occupy the same position in the reference frame. If they do, this would simulate a collision, the two objects involved would be destroyed, and their instances would be removed from the active objects dictionary.</p>

<pre><code>dict actives{ 'missile' : object_c(x1, y1, z1),
              'target'  : object_c(x2, y2, z2),
              'clutter' : object_c(x3, y3, z3),
              ...                               }

...

for key1 in self.actives.keys():
   for key2 in self.actives.keys():
      if not key1 == key2:
         # Get Inertial Positions and Distance
         Pos21 = self.actives[key2].Pos - self.actives[key1].Pos
         distance = math.sqrt(sum(Pos21**2))
         # If Distance &lt;= Critical Distance
         if distance &lt;= 1.0e0
            # Remove key1 and key2 from Actives
            # -- This is where I need help --
</code></pre>

<p>I can't use <code>del</code>:  the keys (and objects) would be removed from actives, but the <code>for</code> loops' conditions fail to recognize this and will encounter a KeyError. What can I do to remove these objects from actives while accessing the keys for the loop conditions?</p>

<p>As you're looping, you can double-check that the key is still present:</p>

<pre><code>for key1 in self.actives.keys():

    if key1 not in self.actives:
        continue

    for key2 in self.actives.keys():

        if key2 not in self.actives:
            continue

        # okay, both keys are still here.  go do stuff
        if not key1 == key2:
</code></pre>

python dictionary