Python Dot Notation Dictionary Access

In most cases I prefer dot notation over bracket notation for dictionary access. That is, I prefer mydictionary.myfield over mydictionary['myflield']. I also prefer attempted access to undefined keys to return None instead of raising an exception.

With the help of this thread, this is what I’ve been using:



class dotdict(dict):
    def __getattr__(self, attr):
        return self.get(attr, None)
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

>>> dd = dotdict()
>>> dd.a
>>> dd.a = 'one'
>>> dd.a
'one'
>>> dd.keys()
['a']

>>> existing = {’a':’A', ‘b’:'B’}
>>> dot_existing = dotdict(existing)
>>> dot_existing.a
‘A’

3 Comments so far

  1. sofeng on October 31st, 2008

    Hi Parand, this seems pretty cool. What would be the best way to convert an existing dict into a dotdict?

  2. Parand on October 31st, 2008

    sofeng, I updated the code above with an example of converting an existing dict to a dotdict. dotdict inherits from dict so for the most part you can do with it anything you can do with a dict.

  3. sofeng on November 3rd, 2008

    Hi Parand, I had a feeling I was asking a stupid question– thanks for updating your example.

Leave a Reply