Convert hash to struct

Discussion in 'Python' started by Amita Ekbote, Jun 19, 2009.

  1. Amita Ekbote

    Amita Ekbote Guest

    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
     
    Amita Ekbote, Jun 19, 2009
    #1
    1. Advertising

  2. Amita Ekbote

    Lie Ryan Guest

    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.
     
    Lie Ryan, Jun 19, 2009
    #2
    1. Advertising

  3. Amita Ekbote

    Lie Ryan Guest

    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
     
    Lie Ryan, Jun 19, 2009
    #3
  4. Amita Ekbote

    Amita Ekbote Guest

    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<> 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
     
    Amita Ekbote, Jun 19, 2009
    #4
  5. Amita Ekbote

    Dave Angel Guest

    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<> 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)
     
    Dave Angel, Jun 19, 2009
    #5
  6. Amita Ekbote

    Jason Guest

    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', 88)), 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 <> 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
     
    Jason, Jun 19, 2009
    #6
  7. 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
     
    Steven D'Aprano, Jun 20, 2009
    #7
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. RA Scheltema
    Replies:
    3
    Views:
    408
    RA Scheltema
    Jan 6, 2004
  2. Chris Fogelklou
    Replies:
    36
    Views:
    1,393
    Chris Fogelklou
    Apr 20, 2004
  3. rp
    Replies:
    1
    Views:
    543
    red floyd
    Nov 10, 2011
  4. Srijayanth Sridhar
    Replies:
    19
    Views:
    629
    David A. Black
    Jul 2, 2008
  5. dt

    convert string to hash of hash?

    dt, Mar 1, 2007, in forum: Perl Misc
    Replies:
    1
    Views:
    470
    ~greg
    Mar 2, 2007
Loading...

Share This Page