Last active
April 8, 2021 12:58
-
-
Save velykanov/83c384edd4be3f5e863d891b40e06f17 to your computer and use it in GitHub Desktop.
Delete key from nested dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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