Convert hash to struct

Nick Craig-Wood nick at
Mon Jun 22 05:29:28 EDT 2009

D'Arcy J.M. Cain <darcy at> wrote:
>  On Fri, 19 Jun 2009 13:17:24 -0500
>  Amita Ekbote <amita.ekbote at> wrote:
> > 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.
>  Are there enough clues here?
>  class MyDict(dict):
>      def __getattribute__(self, name):
>          return dict.__getattribute__(self, name)
>      def __getattr__(self, name):
>          return self.get(name, 42)
>  x = MyDict({'a': 1, 'b': 2, 'values': 3})

That is my preferred solution - subclass dict rather than make a new
type...  I use this a lot for returning results from databases.

Here is a more fleshed out version.  Changing KeyError to
AttributeError is necessary if you want the object to pickle.

class MyDict(dict):
        A dictionary with attribute access also.

        If a builtin dictionary method collides with a member of the
        dictionary, the member function will win.
        def __getattr__(self, name):
                return super(db_dict, self).__getitem__(name)
            except KeyError:
                raise AttributeError("%r object has no attribute %r" % (self.__class__.__name__, name))

        def __setattr__(self, name, value):
            return super(db_dict, self).__setitem__(name, value)

        def __delattr__(self, name):
                return super(db_dict, self).__delitem__(name)
            except KeyError:
                raise AttributeError("%r object has no attribute %r" % (self.__class__.__name__, name))

        def copy(self):
            return MyDict(self)

>  print x.a
>  print x.z
>  print x.values
>  Big question - what should the last line display?  If you expect "3"
>  and not "<built-in method values of MyDict object at 0xbb82838c>" then
>  you need to reconsider the above implementation.  Thinking about the
>  question may change your opinion about this being a good idea after
>  all.


Nick Craig-Wood <nick at> --

More information about the Python-list mailing list