Home  >  Article  >  Backend Development  >  How to simply traverse a dictionary and delete elements in Python

How to simply traverse a dictionary and delete elements in Python

高洛峰
高洛峰Original
2017-02-22 16:27:481788browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn