Reputation: 1227
I have a nested dictionary that's updated dynamically so I never know how many levels there are. What I need to do is delete all entries in the dictionary that equal a given key like "command" for example.
I've tried looping through the dict but I found that the number of levels change at runtime so that didn't work. I was thinking that maybe this should use recursion but I would like to avoid that if I can. I have include a sample of a mock dict, what I want is all keys that = command to be removed.
data = {
'id': 1,
'name': 'Option 1',
'command': do_something,
'sub_opt': {
'id': 10,
'name': 'Sub Option',
'command': do_something_more,
'sub_sub_opt': {
'id': 100,
'name': 'Sub Sub Option',
'command': do_something_crazy,
}
}
}
Upvotes: 0
Views: 64
Reputation: 2188
I know you're trying to avoid recursion, but the code isn't all that bad. Here's an example. (I changed the the values of 'command' keys to strings.)
def delete(data, key):
data.pop(key, None)
for k, v in data.items():
if isinstance(v, dict):
delete(v, key)
delete(data, 'command')
print(data)
{'id': 1, 'name': 'Option 1', 'command': 'do_something', 'sub_opt': {'id': 10, 'name': 'Sub Option', 'command': 'do_something_more', 'sub_sub_opt': {'id': 100, 'name': 'Sub Sub Option', 'command': 'do_something_crazy'}}}
{'id': 1, 'name': 'Option 1', 'sub_opt': {'id': 10, 'name': 'Sub Option', 'sub_sub_opt': {'id': 100, 'name': 'Sub Sub Option'}}}
Upvotes: 1