How to implement 2-D array using UserDict?
jepler epler
jepler.lnk at lnk.ispi.net
Thu Aug 3 18:41:43 EDT 2000
On Thu, 03 Aug 2000 04:29:58 GMT, Courageous
<jkraska1 at san.rr.com> wrote:
>Sam Wun wrote:
>>
>> I want to do something like:
>>
>> import UserDict
>> dict = UserDict.UserDict()
>> dict["Section"]["key"] = "some value"
Strangely enough, I wrote code in another context which could serve you
here.
two_dee_dict = DefaultingDict({})
print two_dee_dict[0][1] # Exception, not defined
two_dee_dict[2][3] = 1
print two_dee_dict[2][3] # prints 1
print two_dee_dict[0] # prints {}
print two_dee_dict[2] # prints {3: 1}
Of course, you can also just write
x = {}
print x[0,1] # Exception, not defined
x[2,3] = 1
print x[2,3] # prints 1
print x # prints {(2,3): 1}
------------------------------------------------------------------------
import UserDict, copy
class DefaultingDict(UserDict.UserDict):
def __init__(self, default=None):
self.default = default
UserDict.UserDict.__init__(self)
def __getitem__(self, key):
try:
return self.data[key]
except:
self.data[key] = copy.copy(self.default)
return self.data[key]
def _test():
x = DefaultingDict(0)
x[1] = 1
print x[0]
print x[1]
x = DefaultingDict([])
print x[0]
x[0].append("item")
print x[0]
x[0].append("item2")
print x[0]
if __name__ == '__main__': _test()
------------------------------------------------------------------------
More information about the Python-list
mailing list