Faqts : Business : Programming : Shopping For You : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 25 people (28%) answered Yes
Recently 0 of 10 people (0%) answered Yes

Entry

Nested dictionaries

Dec 18th, 2009 12:15
new acct, Shopping Snooper, justin hamp, Casino Vendor Directory, engatoo engatoo, osososo didididi, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 359, Felix Thibault


"""
Packages: basic_datatypes.dictionaries
"""

"""
From:           	felixt@dicksonstreet.com (Felix Thibault)
Subject:        	Newbie question about __getattr__ and __setattr__
Date sent:      	Sat, 09 Oct 1999 03:48:02 GMT
To:             	python-list@python.org

I'm trying to learn Python by writing a gui for a
screen-saver program (xlock). To store the 
default settings I was using nested dictionaries,
and they seemed like they could be generally 
useful, so I ended up with this class:
"""

from UserDict import UserDict

class Nester(UserDict):
    def __add__(self, other):
      sum =self.addentry(self.data, other)
      return Nester(sum)

    __radd__ = __add__
      

    def addentry(self, a, b):
        DualValueError =  "Dictionaries assign different values with
same key"
        try:
            sum = a.copy()
            for key in b:
                if key in sum and sum[key] != b[key]:
                    sum[key] = [sum[key] , b[key]]
                    sum[key] = self.addentry(sum[key][0], sum[key][1])
                else:
                    sum[key] = b[key]
            return sum
        except AttributeError:
            raise DualValueError

"""
which I use like this:
"""

i = Nester({'a': {'b': {'c': 'd'}}})
print i
# {'a': {'b': {'c': 'd'}}}
i += {'a':{'b':{'e':'f'}}}
print i
# {'a': {'b': {'c': 'd', 'e': 'f'}}}