图字典输出RuntimeError



我有一个列表字典:

g = {'a': ['b', 'c'], 'b': ['a', 'd', 'e']}

,其中一些值不作为键表示。我想添加所有的值,作为空列表的键,它不存在于键中。目前我正在尝试这样做:

for keys, values in g.items():
for value in values:
if value not in keys:
g[value] = []

运行上面的代码会得到一个回溯:RuntimeError: dictionary changed size during iteration。我在Stackoverflow中检查了其他相关问题,但找不到相关任务。

我希望得到以下输出:

{'a': ['b', 'c'], 'b': ['a', 'd', 'e'], 'c': [], 'd': [], 'e': []}

解决方案

g = {'a': ['b', 'c'], 'b': ['a', 'd', 'e']}
for keys, values in list(g.items()):
for value in values:
if value not in g:
g[value] = []
print(g)

解释关于使用list()的更多信息,请参考Stack Overflow post。此外,您的条件应该检查value是否在g中,而不是在keys中。

最新更新