Adding Syntactic Sugar to Python dicts


This little snippet allows dict keys to be accessed like attributes. For example

d = CustomDict({"foo": "bar", "bah": {"baz": "bot"}})

Can be accessed like # returns "bar" # 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())

Share on: TwitterFacebookGoogle+Email

Comments !