Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #6465 -- Tweaked MergeDict.getlist() to work with Django's Mult…

…iValueDict class. Thanks, Matt McClanahan.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@7062 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 2542b94fb214847af0a4e1eca84558debbf32ee2 1 parent f467c8c
Malcolm Tredinnick authored February 03, 2008
9  django/utils/datastructures.py
@@ -2,6 +2,9 @@ class MergeDict(object):
2 2
     """
3 3
     A simple class for creating new "virtual" dictionaries that actually look
4 4
     up values in more than one dictionary, passed in the constructor.
  5
+
  6
+    If a key appears in more than one of the passed in dictionaries, only the
  7
+    first occurrence will be used.
5 8
     """
6 9
     def __init__(self, *dicts):
7 10
         self.dicts = dicts
@@ -25,11 +28,9 @@ def get(self, key, default=None):
25 28
 
26 29
     def getlist(self, key):
27 30
         for dict_ in self.dicts:
28  
-            try:
  31
+            if key in dict_.keys():
29 32
                 return dict_.getlist(key)
30  
-            except KeyError:
31  
-                pass
32  
-        raise KeyError
  33
+        return []
33 34
 
34 35
     def items(self):
35 36
         item_list = []
13  tests/regressiontests/datastructures/tests.py
@@ -20,6 +20,19 @@
20 20
 >>> md2['chris']
21 21
 'cool'
22 22
 
  23
+MergeDict can merge MultiValueDicts
  24
+>>> multi1 = MultiValueDict({'key1': ['value1'], 'key2': ['value2', 'value3']})
  25
+>>> multi2 = MultiValueDict({'key2': ['value4'], 'key4': ['value5', 'value6']})
  26
+>>> mm = MergeDict(multi1, multi2)
  27
+
  28
+# Although 'key2' appears in both dictionaries, only the first value is used.
  29
+>>> mm.getlist('key2')
  30
+['value2', 'value3']
  31
+>>> mm.getlist('key4')
  32
+['value5', 'value6']
  33
+>>> mm.getlist('undefined')
  34
+[]
  35
+
23 36
 ### MultiValueDict ##########################################################
24 37
 
25 38
 >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})

0 notes on commit 2542b94

Please sign in to comment.
Something went wrong with that request. Please try again.