Last active
March 15, 2022 14:24
-
-
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
This file contains 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
# 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