Convert hash to struct

Lie Ryan lie.1296 at
Fri Jun 19 14:52:34 EDT 2009

Amita Ekbote wrote:
>  Hello,
> 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.
> Thanks
> Amita

You may be able to update the class' dict:

>>> class MyDB(object):
...     def __init__(self, di):
...         self.__dict__.update(di)
>>> di = {'a':10, 'b': 20}
>>> d = MyDB(di)
>>> d
<__main__.MyDB object at 0x7f756b0d0b90>
>>> d.a
>>> d.b

but this might be a security risk, if you cannot trust the database or
its content.

It is much preferrable to use something like:

>>> class MyDB(object):
...     def __init__(self, di):
...         self.a = di['a']
...         self.b = di['b']

since you now have full control of what collumns can go in and whatnot.

More information about the Python-list mailing list