Skip to content

Instantly share code, notes, and snippets.

@dcragusa
Created September 6, 2018 12:24
Show Gist options
  • Save dcragusa/389c07b5140b0f36e7874d1181f87600 to your computer and use it in GitHub Desktop.
Save dcragusa/389c07b5140b0f36e7874d1181f87600 to your computer and use it in GitHub Desktop.
A couple of helpful extensions to dict objects
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