faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

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

6 of 8 people (75%) answered Yes
Recently 5 of 7 people (71%) answered Yes

Entry

Nested dictionaries

Jul 5th, 2000 10:03
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 359, Felix Thibault


"""
Packages: basic_datatypes.dictionaries
"""
"""
From:           	[email protected] (Felix Thibault)
Subject:        	Newbie question about __getattr__ and __setattr__
Date sent:      	Sat, 09 Oct 1999 03:48:02 GMT
To:             	[email protected]
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.keys():
                if sum.has_key(key) 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 = i+{'a':{'b':{'e':'f'}}}
print i
# {'a': {'b': {'c': 'd', 'e': 'f'}}}