【问题标题】:How to change a dictionary while iterating over its keys while iterating over a list如何在迭代列表时迭代其键时更改字典
【发布时间】:2019-06-07 06:30:17
【问题描述】:
  1. 我有一个列表 l。
  2. 我有一本字典 d.

我想遍历 l。对于任何列表项,我都想遍历 d.keys。

如果满足某些条件,我想“更新”我的字典。

我天真地尝试嵌套两个 for 循环并放入一个 if 语句——一个不能改变一个正在迭代的对象的长度。

d = {'this': '1', 'is': '2', 'a': '3', 'list': '4'}

l = ['A', 'B', 'C', 'D', 'E']

for word in l:
    for key in d.keys():
        if len(key) < 2:#some condition
            d.pop(key)
        else:
            print(word, key)

这是我得到的输出:

A this
A is
Traceback (most recent call last):
  File "untitled3.py", line 6, in <module>
    for key in d.keys():
RuntimeError: dictionary changed size during iteration

【问题讨论】:

  • 我认为应该使用与条件不匹配的键构建一个新字典

标签: python python-3.x dictionary for-loop iteration


【解决方案1】:

您可以遍历副本,而不是循环遍历 d

d = {'this': '1', 'is': '2', 'a': '3', 'list': '4'}

l = ['A', 'B', 'C', 'D', 'E']

for word in l:
    for key in d.copy().keys(): # Notice the change
        if len(key) < 2:#some condition
            d.pop(key)
        else:
            print(word, key)

【讨论】:

  • 复制整个字典len(l) 次可能有点贵。同样要遍历字典的键,您只需使用for key in d.copy():,无需访问keys()
【解决方案2】:

在遍历字典的视图时不应更改字典的大小。相反,您可以构建一个新字典并然后打印任何您喜欢的内容。例如:

d = {'this': '1', 'is': '2', 'a': '3', 'list': '4'}
L = ['A', 'B', 'C', 'D', 'E']

d_new = {k: v for k, v in d.items() if len(k) >= 2}

for word in L:
    for key in d_new:
        print(word, key)

the docs中所述:

dict.keys()dict.values() 和返回的对象 dict.items() 是视图对象。他们提供了一个动态的视图 字典的条目,这意味着当字典改变时, 该视图反映了这些变化...... 在字典中添加或删除条目时迭代视图可能 引发 RuntimeError 或无法遍历所有条目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多