Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Convert hash to struct

Reply
Thread Tools

Convert hash to struct

 
 
Amita Ekbote
Guest
Posts: n/a
 
      06-19-2009
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

--
Amita Ekbote
 
Reply With Quote
 
 
 
 
Lie Ryan
Guest
Posts: n/a
 
      06-19-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

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.
 
Reply With Quote
 
 
 
 
Lie Ryan
Guest
Posts: n/a
 
      06-19-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
>



I just remembered something...

If you used python > 2.6, you may also look at namedtuple
 
Reply With Quote
 
Amita Ekbote
Guest
Posts: n/a
 
      06-19-2009
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<(E-Mail Removed)> 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
>




--
Amita Ekbote
 
Reply With Quote
 
Dave Angel
Guest
Posts: n/a
 
      06-19-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<(E-Mail Removed)> 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)


 
Reply With Quote
 
Jason
Guest
Posts: n/a
 
      06-19-2009
Here's my general-purpose solution for doing this:

class Dict2Class(object):
"""
Update like a dictionary, but expose the keys as class properties.
Sweet!
You can instantiate and update this practically any way you
choose, and
the values are available as class properties.
>>> c = Dict2Class((('fred', 11), ('joe', 8), bob=9)
>>> c.bob

9
>>> c.joe

88

>>> c = Dict2Class({'bob': 88, 'fred': 9})
>>> c.fred

9

>>> c = Dict2Class()
>>> c.bob = 88
>>> c.bob

88

This subclasses plain old object. It could also subclass dict to
provide
even more functionality, but at the risk of naming collisions
between
the dict methods and property names.
"""
def __init__(self, *e, **f):
self.__dict__ = dict(*e, **f)
def update(self, *e, **f):
self.__dict__.update(*e, **f)
# Looks a little complex, but it rocks.



On Jun 19, 2:17*pm, Amita Ekbote <(E-Mail Removed)> 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
>
> --
> Amita Ekbote


 
Reply With Quote
 
Steven D'Aprano
Guest
Posts: n/a
 
      06-20-2009
Jason wrote:

> Here's my general-purpose solution for doing this:
>
> class Dict2Class(object):
> """
> Update like a dictionary, but expose the keys as class properties.


I'm afraid that's wrong. It's wrong twice:

* Properties are computed attributes. These are not, they are regular
attributes.

* Class attributes are shared between all instances. These are not, so they
are instance attributes (or just regular "attributes" without
qualification), not class attributes.



> def __init__(self, *e, **f):
> self.__dict__ = dict(*e, **f)


You're updating the instance __dict__, not the class __dict__. Hence they
are instance attributes.

This is the correct thing to do, but if you wanted to share keys and values
between all instances, you would use class attributes:

def __init__(self, *e, **f):
self.__class__.__dict__ = dict(*e, **f)



As far as properties, in this case there's no sensible reason for making
them properties. (Properties have their uses, but this isn't one of them.)
However, since I'm not sensible *grin*, here's a quick-and-dirty version
that works, for some definition of "works":

class Dict2PropertyClass(object):
# Like Dict2Class except using properties.
def __init__(self, *e, **f):
for key, value in dict(*e, **f).items():
private = '_' + key
setattr(self, private, value)
getter = lambda self, private=private: getattr(self, private)
setter = (
lambda self, value, private=private:
setattr(self, private, value)
)
setattr(self.__class__, key,
property(getter, setter)
)


Getting update() working with this version is left as an exercise for the
masochistic *wink*



--
Steven

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Can *common* struct-members of 2 different struct-types, that are thesame for the first common members, be accessed via pointer cast to either struct-type? John Reye C Programming 28 05-08-2012 12:24 AM
hash of hash of hash of hash in c++ rp C++ 1 11-10-2011 04:45 PM
Hash#select returns an array but Hash#reject returns a hash... Srijayanth Sridhar Ruby 19 07-02-2008 12:49 PM
convert string to hash of hash? dt Perl Misc 1 03-02-2007 04:57 AM
struct my_struct *p = (struct my_struct *)malloc(sizeof(struct my_struct)); Chris Fogelklou C Programming 36 04-20-2004 08:27 AM



Advertisments