Created
September 6, 2018 12:24
-
-
Save dcragusa/389c07b5140b0f36e7874d1181f87600 to your computer and use it in GitHub Desktop.
A couple of helpful extensions to dict objects
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
class AttrDict(dict): | |
# access data by dot notation e.g. {'a': 1} -> d.a = 1 | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.__dict__ = self | |
def __getattr__(self, name): | |
return self.get(name, None) | |
class OrderedNestedDict(OrderedDict): | |
# allows for direct nested assignment e.g. d['a'][b'] = 1 -> {'a': {'b': 1}} | |
def __missing__(self, key): | |
result = self[key] = OrderedNestedDict() | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment