Access Python Dictionary Keys As Properties
Say you want to access the values if your dictionary via the dot notation instead of the dictionary syntax. That is, you have:
d = {'name':'Joe', 'mood':'grumpy'}
And you want to get at “name” and “mood” via
d.name
d.mood
instead of the usual
d['name']
d['mood']
Why would you want to do this? Maybe you’re fond of the Javascript Way. Or you find it more aesthetic. In my case I need to have the same piece of code deal with items that are either instances of Django models or plain dictionaries, so I need to provide a uniform way of getting at the attributes.
Turns out it’s pretty simple:
class DictObj(object):
def __init__(self, d):
self.d = d
def __getattr__(self, m):
return self.d.get(m, None)
d = DictObj(d)
d.name
# prints Joe
d.mood
# prints grumpy
Manage your expenses via Email, SMS, Twitter, Voice (Jott: Call and say your expense), IM (Yahoo, AIM, MSN), or Web.
An alternative to this, which I’ve used frequently is to inherit from the dict object itself. This allows for use of normal dict operations and methods and well. This will cause strange errors if you expect your dict to contain keys that collide with the dict method names, however that limitation can be worked around depending on the specifics of the use-case.
It is particulary convenient when the dict in qustion is not yet populated
fully.
I know the following works in 2.4 and 2.5 (probably 2.6 but haven’t tested it):
class DictObj(dict):
def __getattr__(self, name):
try:
return self.__getitem__(name)
except KeyError:
return super(DictObj,self).__getattr__(name)