我得到以下错误:
RuntimeError: dictionary changed size during iteration.
我有以下嵌套字典:
devices = {
'devices': [
{
'id': 'XX',
'is_active': True,
'is_private_session': False,
'is_restricted': False,
'name': 'XX',
'type': 'Computer',
'volume_percent': 100
},
{
'id': 'XX',
'is_active': False,
'is_private_session': False,
'is_restricted': False,
'name': 'XX',
'type': 'Speaker',
'volume_percent': 62
}
]
}
我试图删除一些嵌套的键+值。这就是我正在尝试的:
del_key_list = ['is_private_session', 'is_restricted', 'type', 'volume_percent']
for dictionary in devices['devices']:
for key in dictionary:
if key in del_key_list:
del dictionary[key]
我是否必须使用过滤器或反向列表(list_of_key_i_want_to_save)?
您需要遍历键的副本,以避免在迭代期间更改字典的例外:
for dictionary in devices['devices']:
for key in list(dictionary.keys()): # note a list() here
if key in del_key_list:
del dictionary[key]