【问题标题】:RuntimeError: dictionary changed size during iteration while deleting the key from the dictionaryRuntimeError:从字典中删除键时,字典在迭代期间更改了大小
【发布时间】:2019-08-06 02:26:17
【问题描述】:

我正在尝试从字典中删除一个键。这样做时,我得到了 RuntimeError: dictionary changed size during iteration

myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
    for key in myDict.keys():
        if 'A' in key:
            #print ('exist')
            del myDict['A']
    print(myDict)

想要的

{'B': [('No!', '2')]}

【问题讨论】:

  • 在迭代时不要从某事物(列表、集合、字典)中添加/删除项目。

标签: python dictionary


【解决方案1】:

使用dict理解过滤掉:

{k: v for k, v in myDict.items() if 'A' not in k}

输出:

{'B': [('No!', '2')]}

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多