0

In my code I loop through the keys in a dictionary and if a key matches a condition (existence in another list) the key-value pair is deleted:

for key in my_dict:
    if key in my_list:
        del my_dict[key]

Problem is, when I run the code I get an error: 'dictionary changed size during iteration'. I realize I can't do it with:

for i in range(len(my_dict)):...

since key indices in my dictionary will change with every deletion.

Is there a way to delete elements in a dictionary without raising an error?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
yoni
  • 117
  • 3
  • Providing a fair sample if possible would be great. It saves time on the other end and in most cases early reponse. – LonelySoul Jul 11 '13 at 15:40

4 Answers4

1

there's no need to iterate through all the keys in the dict necessarily

for key in my_list:
    my_dict.pop(key, None)

will do it.

pop here will remove the item if it exists, but doesn't raise an exception if there's a key in my_list which is not in the dict.

ijmarshall
  • 3,373
  • 2
  • 19
  • 13
1

You don't need to loop over your dictionary.

lst  = ['4','8','15','16','23','42']
dct  = {'4':4, 'foo':'bar'}
keys = dct.keys()

for key in lst:
    if key in keys:
        dct.pop(key)
Mathieu Marques
  • 1,678
  • 15
  • 33
0

The answer to this requires copying the dictionary. You need to write a small function I believe. See this thread.

Community
  • 1
  • 1
Dman2
  • 700
  • 4
  • 10
0

You should first create a copy of dict(my) :

my = {2:5, 3:4, 7:9}
lst = [2,7]
del_my = dict(my)


for i in my:
    if i in lst:
        del del_my[i]


print del_my
K DawG
  • 13,287
  • 9
  • 35
  • 66