diff options
| author | ianb <devnull@localhost> | 2006-06-22 05:20:04 +0000 |
|---|---|---|
| committer | ianb <devnull@localhost> | 2006-06-22 05:20:04 +0000 |
| commit | 6c3ebd9dbd7ccda442cc32ccc963b9bf0d605a29 (patch) | |
| tree | 054b5b4888f85a0efe9ea40d85dd595f7016dd4b /paste/util | |
| parent | ff98c3b4872b6bcac687889fccd42f2400de0364 (diff) | |
| download | paste-6c3ebd9dbd7ccda442cc32ccc963b9bf0d605a29.tar.gz | |
Added a method to get a cgi-style dictionary out of this dictionary
Diffstat (limited to 'paste/util')
| -rw-r--r-- | paste/util/multidict.py | 29 |
1 files changed, 27 insertions, 2 deletions
diff --git a/paste/util/multidict.py b/paste/util/multidict.py index 43284b3..e51da3c 100644 --- a/paste/util/multidict.py +++ b/paste/util/multidict.py @@ -6,8 +6,8 @@ class multidict(DictMixin): """ An ordered dictionary that can have multiple values for each key. - Adds the methods getall, getone, and add to the normal dictionary - interface. + Adds the methods getall, getone, mixed, and add to the normal + dictionary interface. """ def __init__(self, *args, **kw): @@ -67,6 +67,29 @@ class multidict(DictMixin): raise KeyError('Multiple values match %r: %r' % (key, v)) return v[0] + def mixed(self): + """ + Returns a dictionary where the values are either single + values, or a list of values when a key/value appears more than + once in this dictionary. This is similar to the kind of + dictionary often used to represent the variables in a web + request. + """ + result = {} + multi = {} + for key, value in self._items: + if key in result: + # We do this to not clobber any lists that are + # *actual* values in this dictionary: + if key in multi: + result[key].append(value) + else: + result[key] = [result[key], value] + multi[key] = None + else: + result[key] = value + return result + def __delitem__(self, key): items = self._items found = False @@ -178,6 +201,8 @@ __test__ = { ['a', 'a', 'b'] >>> d.items() [('a', 1), ('a', 2), ('b', 4)] + >>> d.mixed() + {'a': [1, 2], 'b': 4} >>> multidict([('a', 'b')], c=2) multidict([('a', 'b'), ('c', 2)]) """} |
