Fixed #6465 -- Tweaked MergeDict.getlist() to work with Django's MultiValueDict class. Thanks, Matt McClanahan.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@7062 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Malcolm Tredinnick 2008-02-03 02:02:41 +00:00
parent f467c8cbc1
commit 2542b94fb2
2 changed files with 18 additions and 4 deletions

View File

@ -2,6 +2,9 @@ class MergeDict(object):
""" """
A simple class for creating new "virtual" dictionaries that actually look A simple class for creating new "virtual" dictionaries that actually look
up values in more than one dictionary, passed in the constructor. up values in more than one dictionary, passed in the constructor.
If a key appears in more than one of the passed in dictionaries, only the
first occurrence will be used.
""" """
def __init__(self, *dicts): def __init__(self, *dicts):
self.dicts = dicts self.dicts = dicts
@ -25,11 +28,9 @@ class MergeDict(object):
def getlist(self, key): def getlist(self, key):
for dict_ in self.dicts: for dict_ in self.dicts:
try: if key in dict_.keys():
return dict_.getlist(key) return dict_.getlist(key)
except KeyError: return []
pass
raise KeyError
def items(self): def items(self):
item_list = [] item_list = []

View File

@ -20,6 +20,19 @@
>>> md2['chris'] >>> md2['chris']
'cool' 'cool'
MergeDict can merge MultiValueDicts
>>> multi1 = MultiValueDict({'key1': ['value1'], 'key2': ['value2', 'value3']})
>>> multi2 = MultiValueDict({'key2': ['value4'], 'key4': ['value5', 'value6']})
>>> mm = MergeDict(multi1, multi2)
# Although 'key2' appears in both dictionaries, only the first value is used.
>>> mm.getlist('key2')
['value2', 'value3']
>>> mm.getlist('key4')
['value5', 'value6']
>>> mm.getlist('undefined')
[]
### MultiValueDict ########################################################## ### MultiValueDict ##########################################################
>>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})