Entry
Nested dictionaries
Jul 5th, 2000 10:03
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 2020 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.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'}}}