python基础:映射和集合类型

python字典的迭代器遍历

字典有一个方法可以返回该字典的迭代器,这个方法就是:

dict. iteritems()

当在字典中增加或者删除字典entry的时候,迭代器会失效的,类似于C++的stl。迭代器遍历到头部就会产生错误。

>>> d = {'a': 1, 'b': 2}
>>> di = d.iteritems()
>>> di.next()
('a', 1)
>>> di.next()
('b', 2)
>>> di.next()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
StopIteration

再来看一个迭代器失效的问题:

>>> d = {'a': 1, 'b': 2}
>>> di = d.iteritems()
>>> di.next()
('a', 1)
>>> d['x'] = 'foobar'     # adding a new key:value pair during iterarion;
>>> di.next()             # that raises an error later on
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
原文地址:https://www.cnblogs.com/stemon/p/5100155.html