[Tutor] deleting elements of a dictionary

Peter Otten __peter__ at web.de
Thu May 18 18:05:22 EDT 2017


Michael C wrote:

> I am trying to remove incorrect entries of my dictionary.
> I have multiple keys for the same value,
> 
> ex,
> [111]:[5]
> [222]:[5]
> [333]:[5}
> 
> and I have found out that some key:value pairs are incorrect, and the best
> thing to do
> is to delete all entries who value is 5. So this is what I am doing:
> 
> import numpy
> read_dictionary = numpy.load('loc_string_dictionary.npy').item()
> 
> for n in read_dictionary:
>     print(read_dictionary[n])
>     if read_dictionary[n] == '5':
>         del read_dictionary[n]
> 
> 
> However, I get this error:
> RuntimeError: dictionary changed size during iteration
> 
> and I can see why.
> 
> What's the better thing to do?

You can copy the keys into a list:

  for n in list(read_dictionary):
>     print(read_dictionary[n])
>     if read_dictionary[n] == '5':
>         del read_dictionary[n]

As the list doesn't change size during iteration there'll be no error or 
skipped key aka list item.

If there are only a few items to delete build a list of keys and delete the 
dict entries in a secend pass:

delenda = [k for k, v in read_dictionary.items() if v == "5"]
for k in delenda:
    del read_dictionary[k]

If there are many items to delete or you just want to default to the most 
idiomatic solution put the pairs you want to keep into a new dict:

read_dictionary = {k: v for k, v in read_dictionary.items() if v != "5"}




More information about the Tutor mailing list