Skip to content

Instantly share code, notes, and snippets.

@wolkenarchitekt
Last active March 15, 2022 14:24
Show Gist options
  • Save wolkenarchitekt/675670bd01ee922b0adf63ad8a5d197c to your computer and use it in GitHub Desktop.
Save wolkenarchitekt/675670bd01ee922b0adf63ad8a5d197c to your computer and use it in GitHub Desktop.
A defaultdict like dictionary that allows accessing nested keys without getting KeyErrors or TypeErrors
# Required: boltons, nested_dict
from boltons.iterutils import remap
from nested_dict import nested_dict
def ndict(data):
"""
Create a defaultdict-like dictionary that allows accessing nested keys without getting
KeyErrors or TypeErrors.
Regular dict:
{'a': 'a', 'b': None}['c'] => KeyError
{'a': 'a', 'b': None}['b']['c'] => TypeError
ndict:
{'a': 'a', 'b': None}['c'] => {}
{'a': 'a', 'b': None}['b']['c'] => {}
:param data: dictionary data to convert
:type data: dict
:return:
"""
data = remap(data, lambda p, k, v: v is not None)
return nested_dict(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment