Tuesday, December 7, 2010

attributedict: dictionary whose keys are also attributes

>>> class attributedict(dict):
...    def __init__(self, *a, **kw):
...       self.__dict__ = self
...       dict.__init__(*a, **kw)
...
>>> ad = attributedict()
>>> ad["one"] = 1
>>> ad.one
1
>>> ad.two = 2
>>> ad["two"]
2
>>> attributedict(three=3).three
3


Edit: unsurprisingly, I'm not the first one to come up with this construct.  Here is one example that predates my post by 5 years: http://code.activestate.com/recipes/361668/

No comments:

Post a Comment