Home > Net >  Delete Key Value pair of a nested Dictionary
Delete Key Value pair of a nested Dictionary

Time:04-23

I get the following error:

RuntimeError: dictionary changed size during iteration. 

I have the following nested dictionary:

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

I am trying to delete some of the nested keys value. That's what I am trying:

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]

Do I have to use a filter or an reversed list (list_of_keys_I_want_to_save)?

CodePudding user response:

you need to iterate over a copy of keys to avoid exception of changing a dictionary during iteration:

for dictionary in devices['devices']:
    for key in list(dictionary.keys()):  # note a list() here
        if key in del_key_list:
            del dictionary[key]
  • Related