Convert hash to struct

D'Arcy J.M. Cain darcy at
Fri Jun 19 14:49:09 EDT 2009

On Fri, 19 Jun 2009 13:17:24 -0500
Amita Ekbote <amita.ekbote at> wrote:
> I am retrieving values from a database in the form of a dictionary so
> I can access the values as d['column'] and I was wondering if there is
> a way to convert the hash to a struct like format so i can just say
> d.column. Makes it easier to read and understand.

Are there enough clues here?

class MyDict(dict):
    def __getattribute__(self, name):
        return dict.__getattribute__(self, name)

    def __getattr__(self, name):
        return self.get(name, 42)

x = MyDict({'a': 1, 'b': 2, 'values': 3})

print x.a
print x.z
print x.values

Big question - what should the last line display?  If you expect "3"
and not "<built-in method values of MyDict object at 0xbb82838c>" then
you need to reconsider the above implementation.  Thinking about the
question may change your opinion about this being a good idea after all.

D'Arcy J.M. Cain <darcy at>         |  Democracy is three wolves                |  and a sheep voting on
+1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.

More information about the Python-list mailing list