What you do will throw a parallel modification exception in Java. d.keys() creates a list of keys that exist when it is called, but this list is now static. Changes to d will not change the saved version of d.keys() . Therefore, when you d.keys() over d.keys() , but delete the elements, you get the opportunity to change the key that no longer exists.
You can use d.pop(k, None) , which will return either the value displayed on k , or None if k not. This avoids the KeyError problem.
EDIT: for clarification, to prevent more phantom downmods (no negative feedback problems, just make it constructive and leave a comment so we can have a potentially informative discussion - I'm here to find out as well as help)
It is true that in this particular state he should not be mixed up . I just raised this as a potential problem, because if he uses the same coding scheme in another part of the program where he is not , so careful / lucky that he considers the data structure, such problems can arise. It does not even use a dictionary, but rather a class that implements certain methods, so you can relate to it in a similar way.
nearlymonolith
source share