zoukankan      html  css  js  c++  java
  • 循环字典进行操作时出现:RuntimeError: dictionary changed size during iteration的解决方案

    在做对员工信息增删改查这个作业时,有一个需求是通过用户输入的id删除用户信息。我把用户信息从文件提取出来储存在了字典里,其中key是用户id,value是用户的其他信息。在循环字典的时候,当用户id和字典里的key相等时,会删除这条信息,当时删除时报错RuntimeError: dictionary changed size during iteration。

    for key in staff_info:
        if user_id == key:
            print(key)
            staff_info.pop(key)
            id_exist = True

    参考:https://www.python.org/dev/peps/pep-0234/#dictionary-iterators

    在官网看到解释:

    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.

    意思是多字典在被循环的时候不能被循环删除和更新,除了给一个已经存在的key设置value。还说道 for kin dict: ...和for k in dict.keys(): ...效果是一样的,但是前者速度更快。

    那就来试验一下:

    a = {'a': 1, 'b': 0, 'c': 1, 'd': 0}
    
    for key in a:
        print(key, a[key])
    
    for key in a.keys():
        print(key, a[key])
    
    # 两个循环效果一样
    
    print(a.keys())  # dict_keys(['a', 'b', 'c', 'd'])
    print(a)  # {'a': 1, 'b': 0, 'c': 1, 'd': 0}

    除了a.keys是dict_keys类型,它们的效果是一样的。

    那么解决方案就出来了,转换成列表形式就OK了。

    for key in list(staff_info.keys()):  
        if user_id == key:
            print(key)
            staff_info.pop(key)
            id_exist = True
    有道词典
    for k in dict: ...
    详细X
    k的dict类型:…

  • 相关阅读:
    【转】寻找最好的笔记软件:海选篇 (v1.0)
    【转】git rebase简介(基本篇)
    【转】学会这13个原则写UI界面文案,用户才能秒懂
    sqlserver巧用row_number和partition by分组取top数据
    使用SQL语句清空数据库所有表的数据
    在 SQL Server 2005 中配置数据库邮件
    SQL compute by 的使用
    SQL Cursor 基本用法
    Sqlserver双机热备文档(无域)
    查询分页的几种Sql写法
  • 原文地址:https://www.cnblogs.com/lshedward/p/9988640.html
Copyright © 2011-2022 走看看