Convert hash to struct
Dave Angel
davea at ieee.org
Fri Jun 19 17:52:11 EDT 2009
Amita Ekbote wrote:
> I wanted to make a more generic way of doing this so that even if the
> columns are modified or new ones are added it should be simple. Anyway
> I will reconsider this sort of am implementation. Just out of
> curiosity is there any other way of achieving this?
>
> Thanks
> Amita
>
> On Fri, Jun 19, 2009 at 1:52 PM, Lie Ryan<lie.1296 at gmail.com> wrote:
>
>> 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
>>>>>
>> 10
>>
>>>>> d.b
>>>>>
>> 20
>>
>> 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.
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
You really shouldn't top-post here; it makes the sequence of message
and response very hard to follow. Put your comments at the end, unless
it's a simple "thanks for the response" one-liner.
Someone else pointed out that you can derive from dict, and showed you
why that can be dangerous if one of the attributes you're trying to use
happens to be already a method in the list class.
But you could write a class that *contains* a dict, and gives you access
to it by attribute. Look at this for starters:
class undict(object):
def __init__(self):
self.data = {"key1":44, "key2":90}
def __getattr__(self, name):
try:
return self.data[name]
except KeyError:
raise AttributeError(name)
More information about the Python-list
mailing list