Adding Syntactic Sugar to Python dicts
Snippet
This little snippet allows dict keys to be accessed like attributes. For example
d = CustomDict({"foo": "bar", "bah": {"baz": "bot"}})
Can be accessed like
d.foo # returns "bar"
d.foo.bah.baz # returns "bot"
In addition to the hash key lookups.
class CustomDict(dict):
def __init__(self, data):
d = data.copy()
self.__dict__ = self
for key, value in data.iteritems():
if isinstance(value, dict):
d[key] = CustomDict(value)
map(self.__setitem__, d.keys(), d.values())
Comments !