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’
Manage your expenses via Email, SMS, Twitter, Voice (Jott: Call and say your expense), IM (Yahoo, AIM, MSN), or Web.
Hi Parand, this seems pretty cool. What would be the best way to convert an existing dict into a dotdict?
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.
Hi Parand, I had a feeling I was asking a stupid question– thanks for updating your example.