Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Tuesday, July 3, 2012

Override Python dictionary to easily access dictionary entries as an attribute

Accessing python dictionary by attribute instead of [key] is easy if you override the dictionary class and provide the __getattr__ and __setattr__ methods as shown in MyDict class.


Before
old = {}
old['Name'] = 'Daffy'
old['Age'] = 30

After
new = MyDict()
new.Name = 'Micky'
new.Age = 30

print values['Name'], values.Name

print len(values.keys())

class MyDict(dict):
    def __init__(self):
        pass


    def __getattr__(self, name):
        return = self.get(name, '')


    def __setattr__(self, name, value):
        self[name] = value


    def __delattr__(self, name):
        if name in self:
            del self[name]