删除嵌套字典的键值对

Delete Key Value pair of a nested Dictionary

我收到以下错误:

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_keys_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]