for e in exam.keys():
if exam[e] == '':
del exam[e]
for e in exam:
使用的是迭代器,它等于:
>>> exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }
>>> fetch = iter(exam)
>>> while True:
... try:
... key = fetch.next()
... except StopIteration:
... break
... if exam[key] == '':
... del exam[key]
...
只是在for循环中,它会自动调用next方法!
字典的迭代器会遍历它的键,在这个过程中,不能改变这个字典!exam.keys()返回的是一个独立的列表。
下面是来自PEP234的snapshot:
Dictionaries implement a tp_iter slot that returns an efficient
iterator that iterates over the keys of the dictionary. During
such an iteration, the dictionary should not be modified, except
that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method).