


Let’s first review some basic methods of traversing dictionaries in Python:
Script:
#!/usr/bin/python dict={"a":"apple","b":"banana","o":"orange"} print "##########dict######################" for i in dict: print "dict[%s]=" % i,dict[i] print "###########items#####################" for (k,v) in dict.items(): print "dict[%s]=" % k,v print "###########iteritems#################" for k,v in dict.iteritems(): print "dict[%s]=" % k,v print "###########iterkeys,itervalues#######" for k,v in zip(dict.iterkeys(),dict.itervalues()): print "dict[%s]=" % k,v
Execution results:
##########dict###################### dict[a]= apple dict[b]= banana dict[o]= orange ###########items##################### dict[a]= apple dict[b]= banana dict[o]= orange ###########iteritems################# dict[a]= apple dict[b]= banana dict[o]= orange ###########iterkeys,itervalues####### dict[a]= apple dict[b]= banana dict[o]= orange
Well, then we enter the "main topic"--
A paragraph about Python dictionary traversal" Debate"....
Excerpt first:
#这里初始化一个dict >>> d = {'a':1, 'b':0, 'c':1, 'd':0} #本意是遍历dict,发现元素的值是0的话,就删掉 >>> for k in d: ... if d[k] == 0: ... del(d[k]) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration #结果抛出异常了,两个0的元素,也只删掉一个。 >>> d {'a': 1, 'c': 1, 'd': 0} >>> d = {'a':1, 'b':0, 'c':1, 'd':0} #d.keys() 是一个下标的数组 >>> d.keys() ['a', 'c', 'b', 'd'] #这样遍历,就没问题了,因为其实其实这里遍历的是d.keys()这个list常量。 >>> for k in d.keys(): ... if d[k] == 0: ... del(d[k]) ... >>> d {'a': 1, 'c': 1} #结果也是对的 >>> #这里初始化一个dict >>> d = {'a':1, 'b':0, 'c':1, 'd':0} #本意是遍历dict,发现元素的值是0的话,就删掉 >>> for k in d: ... if d[k] == 0: ... del(d[k]) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration #结果抛出异常了,两个0的元素,也只删掉一个。 >>> d {'a': 1, 'c': 1, 'd': 0} >>> d = {'a':1, 'b':0, 'c':1, 'd':0} #d.keys() 是一个下标的数组 >>> d.keys() ['a', 'c', 'b', 'd'] #这样遍历,就没问题了,因为其实其实这里遍历的是d.keys()这个list常量。 >>> for k in d.keys(): ... if d[k] == 0: ... del(d[k]) ... >>> d {'a': 1, 'c': 1} #结果也是对的 >>>
In fact, this problem is very simple, that is, if you traverse a dictionary, but If it is changed during the traversal, such as adding or deleting an element, the traversal will exit and an exception of dictionary changed size during iteration will be thrown.
The solution is to traverse the dictionary key value and traverse based on the dictionary key value. Changing the value in this way will not affect the continuation of the traversal.
But here is another great expert who gives a high opinion:
First of all, python recommends the use of iterators, that is, for k in adict form. Secondly, deleting elements in the container during traversal is not recommended in libraries such as C++ STL and Python, because this situation often indicates that there is a problem with your design plan, and all have special requirements, which correspond to python. , just use adict.key() to make a copy. Finally, all Python containers do not promise thread safety. If you want to do this with multiple threads, you must lock it. This also shows that there is a problem with the business code design.
But by "Traversing In the special case of "delete specific elements", I came to the conclusion that "when traversing dict, develop the habit of using for k in d.keys()", I think it is necessary to correct it. In ordinary traversal, you should use for k in adict.
In addition, for the requirement of "removing elements during traversal", the pythonic approach is adict = {k, v for adict.iteritems() if v != 0} or alist = [i for i in alist if i ! = 0]
This way of writing made my eyes light up: Why is there still this syntax?
Looking carefully, he may mean this:
#!/usr/bin/env python # -*- coding=utf-8 -*- a = {'a':1, 'b':0, 'c':1, 'd':0} b={} for k,v in a.items(): if v != 0: b.update({k:v}) adict = b del b print a #!/usr/bin/env python # -*- coding=utf-8 -*- a = {'a':1, 'b':0, 'c':1, 'd':0} b={} for k,v in a.items(): if v != 0: b.update({k:v}) adict = b del b print a
I don’t know if it’s right.
Because this way of writing suddenly made me think of the ternary operator at first. After a closer look, I realized that it was not the case. There was a solution in Google before
val = float(raw_input("Age: ")) status = ("working","retired")[val>65] print "You should be",status val = float(raw_input("Age: ")) status = ("working","retired")[val>65] print "You should be",status
val>65 is a logical expression, returning 0 or 1, which happens to be the ID of the previous tuple, which is really wonderful. . .
But there is also a version in Google's information
#V1 if X else V2 s = None a = "not null" if s == None else s print a #'not null'
Later, I posted a post and mentioned it in the Huaman user group (Chinese Python technical mailing list) Many experts have answered as follows:
>>> alist = [1,2,0,3,0,4,5] >>> alist = [i for i in alist if i != 0] >>> alist [1, 2, 3, 4, 5] >>> d = {'a':1, 'b':0, 'c':1, 'd':0} >>> d = dict([(k,v) for k,v in d.iteritems() if v!=0]) >>> d {'a':1,'c':1'}
If it is larger than Python>=2.7
, you can also use this writing method:
>>> d = {k:v for k,v in d.iteritems() if v !=0 }
For more related articles about exceptions caused by changing elements during dictionary traversal in Python, please pay attention to the PHP Chinese website!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
