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

How to simply traverse a dictionary and delete elements in Python

高洛峰
Release: 2017-02-22 16:27:48
Original
1867 people have browsed it

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)
Copy after login

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)
Copy after login

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)
Copy after login


For more Python methods to simply traverse the dictionary and delete elements, please pay attention to the PHP Chinese website!

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template