I need a special dictionary that would do as follows:
if key is set to more than once, the values are a list of all set values. Such a list is returned as value on get.
if key is set only once, it is set to that value, and returned as value as well.
Sort of like MultiDict from Paste, but that does not seem to have the same interface as ordinary dict.
I wrote this:
class ModalDict(dict):
def __init__(self, *args, **kwargs):
class Speclist(list):
pass
self.speclist = Speclist
dict.__init__(self, *args, **kwargs)
def __getitem__(self, k):
v = dict.__getitem__(self, k)
if isinstance(v, self.speclist) and len(v) == 1:
return v[0]
return v
def __setitem__(self, k, v):
self.setdefault(k, self.speclist()).append(v)
Obviously I defined Speclist to differentiate it from regular list that someone may set as value.
Problems? Any better way to do this?