


Perfect solution to the problem of error reporting when Python traverses and deletes empty elements in the dictionary
下面小编就为大家带来一篇完美解决python遍历删除字典里值为空的元素报错问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }
使用下列遍历的方法删除:
1. for e in exam:
2. if exam[e] == '':
3. del exam[e]
结果出现下列错误,怎么解决:
Traceback (most recent call last): File "Untitled.py", line 3, in <module> for e in exam: RuntimeError: dictionary changed size during iteration
正确做法:
1. s = {"1":a,"2":b,"3":c,"4":d,"5":e}
2. s_key = list(s.keys())
3. for k_s in s_key:
4.#比如我要删除第四个元素
5.del s["4"]
只是在for循环中,相当于对链表的操作,它会自动调用next方法!
字典的迭代器会遍历它的键,在这个过程中,不能改变这个字典!不能删除、添加数据
要先记录要删除的元素的索引,遍历完后再删除,exam.keys()返回的是一个独立的列表
以上这篇完美解决python遍历删除字典里值为空的元素报错问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持PHP中文网。
更多完美解决python遍历删除字典里值为空的元素报错问题相关文章请关注PHP中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H
