All pastes #294424 Raw Edit

Stuff

public python v1 · immutable
#294424 ·published 2006-12-28 13:41 UTC
rendered paste body
class listdict(dict):    """    Dictionnary storing list of values instead of value.    "self[key] = value" appends value to self[key] list (or create new list).    Classic constructors:    >>> listdict()    {}    >>> listdict({"un": 1, "deux": 2})    {'un': [1], 'deux': [2]}    >>> listdict(un=1, deux=2)    {'un': [1], 'deux': [2]}    Construction using tuple:    >>> listdict((("un", 1), ("deux", 2)))    {'un': [1], 'deux': [2]}    >>> listdict((("un", 1), ("deux", 2)), trois=4)    {'un': [1], 'trois': [4], 'deux': [2]}    """    def __init__(self, *args, **kw):        dict.__init__(self)        if args:            if 1 < len(args):                raise ValueError(                    "listdict expected at most 1 arguments, got %u"                    % len(args))            data = args[0]            if isinstance(data, (list, tuple)):                self._initWithTuple(data)            else:                self._initWithDict(data)        if kw:            self._initWithDict(kw)    def _initWithTuple(self, data):        for (k, v) in data:            dict.__setitem__(self, k, [v])    def _initWithDict(self, data):        for (k, v) in data.iteritems():            if isinstance(v, list):                dict.__setitem__(self, k, v)            elif isinstance(v, tuple):                dict.__setitem__(self, k, list(v))            else:                dict.__setitem__(self, k, [v])    def __setitem__(self, key, value):        try:            self[key].append(value)        except KeyError:            dict.__setitem__(self, cle, [valeur,])if __name__ == "__main__":    import doctest    print "Test module"    print "Result: error: %u, test: %u" % doctest.testmod()