Skip to content

Instantly share code, notes, and snippets.

@velykanov
Last active April 8, 2021 12:58
Show Gist options
  • Save velykanov/83c384edd4be3f5e863d891b40e06f17 to your computer and use it in GitHub Desktop.
Save velykanov/83c384edd4be3f5e863d891b40e06f17 to your computer and use it in GitHub Desktop.
Delete key from nested dictionary
def delete(key, dict_obj):
"""Deletes element from dict_obj accessing by complex key
Args:
key (str): Complex key to your value (separated by dots)
dict_obj (dict): Your dictionary
Raises:
KeyError: if object doesn't contain key
Example:
>>> d = {
'a': 2,
'b': {
'c': {'d': 3},
'd': {
'e': 5,
'f': 7,
},
},
}
>>> delete('b.d.e', d)
>>> print(d)
{
'a': 2,
'b': {
'c': {'d': 3},
'd': {'f': 7},
},
}
"""
key, *tail = key.split('.', 1)
if tail:
delete(tail[0], dict_obj[key])
else:
del dict_obj[key]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment