All pastes #294342 Raw Edit

Miscellany

public python v1 · immutable
#294342 ·published 2006-12-28 11:22 UTC
rendered paste body
class listdict(dict):    """    >>> listdict({"un": 1, "deux": 2})    {'un': [1], 'deux': [2]}    >>> listdict(un=1, deux=2)    {'un': [1], 'deux': [2]}    >>> listdict((("un", 1), ("deux", 2)))    {'un': [1], '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))            kw = args[0]            if isinstance(kw, (list, tuple)):                for (k, v) in kw:                    dict.__setitem__(self, k, [v])                return        for (k, v) in kw.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"    doctest.testmod()