in code loop through keys in dictionary , if key matches condition (existence in list) key-value pair deleted:
for key in my_dict: if key in my_list: del my_dict[key]
problem is, when run code error: 'dictionary changed size during iteration'. realize can't with:
for in range(len(my_dict)):...
since key indices in dictionary change every deletion.
is there way delete elements in dictionary without raising error?
you don't need loop on dictionary.
lst = ['4','8','15','16','23','42'] dct = {'4':4, 'foo':'bar'} keys = dct.keys() key in lst: if key in keys: dct.pop(key)
Comments
Post a Comment