python遍历字典删除元素错误

作者: 生信编程日常 | 来源:发表于2020-01-31 20:11 被阅读0次

    今天写了这么一段代码,类似于这样:

    d = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5}
    for key in d:
        if key == 'three':
            del d[key]
    

    这里报了一个这样的错误:
    RuntimeError: dictionary changed size during iteration;

    去查了一下,发现官方的一个解释:
    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). This means that we can write

    for k in dict: ...
    which is equivalent to, but much faster than

    for k in dict.keys(): ...
    as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

    也就是说在迭代字典的时候,每次迭代不得循环删除或者更新字典。并且提到for k in dict与for k in dict.keys()功能一样,并且更快。

    这个错误的解决方式是将keys转化为列表迭代:

    keys = list(d.keys())
    for key in keys:
        if key == 'three':
            del(d[key])
    

    字典d返回:
    {'one': 1, 'two': 2, 'four': 4, 'five': 5}

    欢迎关注公众号!


    生信编程日常

    相关文章

      网友评论

        本文标题:python遍历字典删除元素错误

        本文链接:https://www.haomeiwen.com/subject/voywthtx.html