Python遍历删除字典报错:dictionary changed size during iteration

        在尝试遍历Python的dict,然后删除key为某些值的数据的时候,出现报错信息:

dictionary changed size during iteration

        我们刚开始代码大概是这样:

for key in results.keys():
    if key == xxid:
        results.pop(key)

        查看官方文档:PEP 234 -- Iterators | Python.orgThe official home of the Python Programming Languagehttps://www.python.org/dev/peps/pep-0234/Python遍历删除字典报错:dictionary changed size during iteration_第1张图片

        大概意思就是指在遍历字典的时候添加、删除、修改操作是不被允许的,因此如果需要删除,可以将字典转换为list进行删除。修改后代码:

for key in list(results.keys()):
    if key == xxid:
        results.pop(key)

         也可以使用del删除:

for key in list(results.keys()):
    if key == xxid:
        del results[key]

你可能感兴趣的:(Python,debuger,python)