我正在尝试删除 键形成一个多级字典。我创建字典的代码如下:
from collections import defaultdict
f = lambda: defaultdict(f)
d = f()
d['A']['B1']['C1'] = 1
d['A']['B1']['C2'] = 2
d['A']['B1']['C3'] = 3
d['A']['B2']['C1'] = 15
d['A']['B2']['C2'] = 20
现在我正在尝试删除“ C3 ”键。字典的最终结构是:
{
"A": {
"B1": {
"C1": 1,
"C2": 2
},
"B2": {
"C1": 15,
"C2": 20
}
}
}
我的尝试:
for level_1_key, level_1_dct in d.items():
for level_2_key, level_2_dct in level_1_dct.items():
for level_3_key, level_value in level_2_dct.items():
if level_value == 3:
d[level_1_key][level_2_key].pop(level_3_key, 'None')
我在运行上面的代码时收到以下错误:
RuntimeError: dictionary changed size during iteration
所以有人可以帮我解决并理解这个问题。
答案 0 :(得分:0)
错误消息可以准确地告诉您问题所在。当您仍在迭代字典时,您正试图删除该项目,这在python中是不可能的。相反,您应该保留对项目路径的引用,并在完成迭代后将其删除:
paths = []
for level_1_key, level_1_dct in d.items():
for level_2_key, level_2_dct in level_1_dct.items():
for level_3_key, level_value in level_2_dct.items():
if level_value == 3:
paths.append((level_1_key, level_2_key, level_3_key))
for lvl1, lvl2, lvl3 in paths:
d[lvl1][lvl2].pop(lvl3, None)