Home > Article > Backend Development > How to simply traverse a dictionary and delete elements in Python
The example in this article describes how to simply traverse a dictionary and delete elements in Python. Share it with everyone for your reference, the details are as follows:
There must be something wrong with this method:
d = {'a':1, 'b':2, 'c':3} for key in d: d.pop(key)
will report this Error: RuntimeError: dictionary changed size during iteration
This method is feasible for Python2, but Python3 still reports the above error.
d = {'a':1, 'b':2, 'c':3} for key in d.keys(): d.pop(key)
The reason why Python3 reports an error is that the keys() function returns dict_keys instead of list. The possible methods for Python3 are as follows:
d = {'a':1, 'b':2, 'c':3} for key in list(d): d.pop(key)
For more Python methods to simply traverse the dictionary and delete elements, please pay attention to the PHP Chinese website!