#How do I delete a key in deictionary when iterating through the dictionary?
for k in lst_keywords_physics_dict.keys():
if (len(k)==1):
lst_keywords_physics_dict.pop(k)
break
CodePudding user response:
#We can use this method in python 3 to delete the keys when iterating throug the dictionary without getting the error regarding changing size of dictionary.
for k in list(lst_keywords_physics_dict.keys()):
if (len(k)<3):
lst_keywords_physics_dict.pop(k)
CodePudding user response:
You are already doing it correctly.
for example:
lst_keywords_physics_dict = {'a': 1, 'b': 2}
for k in lst_keywords_physics_dict.keys():
if len(k) == 1:
lst_keywords_physics_dict.pop(k)
break
So, what was the issue you were facing? , I can modify the answer accordingly.