Convert hash to struct

A

Amita Ekbote

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
 
L

Lie Ryan

Amita said:
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:
.... def __init__(self, di):
.... self.__dict__.update(di)
....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:
.... 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.
 
L

Lie Ryan

Amita said:
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
 
A

Amita Ekbote

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

Amita said:
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:
... def __init__(self, di):
... self.__dict__.update(di)
...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:
... 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.
 
D

Dave Angel

Amita said:
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

Amita said:
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

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.
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)
 
J

Jason

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. 88
9
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.



 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
 
S

Steven D'Aprano

Jason said:
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*
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top