Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #12375 -- Added a dict() method to convert a MultiValueDict (su…

…ch as a QueryDict) to a dictionary of key-value pairs. Thanks, oinopion and hvdklauw.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16418 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 97f22f29699476d5bcbbf599a3dba22909f4ec85 1 parent dfa2916
Jannis Leidel authored June 16, 2011
6  django/utils/datastructures.py
@@ -391,6 +391,12 @@ def update(self, *args, **kwargs):
391 391
         for key, value in kwargs.iteritems():
392 392
             self.setlistdefault(key, []).append(value)
393 393
 
  394
+    def dict(self):
  395
+        """
  396
+        Returns current object as a dict with singular values.
  397
+        """
  398
+        return dict((key, self[key]) for key in self)
  399
+
394 400
 class DotExpandedDict(dict):
395 401
     """
396 402
     A special dictionary constructor that takes a dictionary in which the keys
12  docs/ref/request-response.txt
@@ -482,6 +482,18 @@ In addition, ``QueryDict`` has the following methods:
482 482
         >>> q.lists()
483 483
         [(u'a', [u'1', u'2', u'3'])]
484 484
 
  485
+.. method:: QueryDict.dict()
  486
+
  487
+    .. versionadded:: 1.4
  488
+
  489
+    Returns ``dict`` representation of ``QueryDict``. For every (key, list)
  490
+    pair in ``QueryDict``, ``dict`` will have (key, item), where item is one
  491
+    element of the list, using same logic as :meth:`QueryDict.__getitem__()`::
  492
+
  493
+        >>> q = QueryDict('a=1&a=3&a=5')
  494
+        >>> q.dict()
  495
+        {u'a': u'5'}
  496
+
485 497
 .. method:: QueryDict.urlencode([safe])
486 498
 
487 499
     Returns a string of the data in query-string format. Example::
12  tests/regressiontests/utils/datastructures.py
@@ -235,6 +235,18 @@ def test_copy(self):
235 235
             self.assertEqual(d1["key"], ["Penguin"])
236 236
             self.assertEqual(d2["key"], ["Penguin"])
237 237
 
  238
+    def test_dict_translation(self):
  239
+        mvd = MultiValueDict({
  240
+            'devs': ['Bob', 'Joe'],
  241
+            'pm': ['Rory'],
  242
+        })
  243
+        d = mvd.dict()
  244
+        self.assertEqual(d.keys(), mvd.keys())
  245
+        for key in mvd.keys():
  246
+            self.assertEqual(d[key], mvd[key])
  247
+
  248
+        self.assertEqual({}, MultiValueDict().dict())
  249
+
238 250
 
239 251
 class DotExpandedDictTests(DatastructuresTestCase):
240 252
 

0 notes on commit 97f22f2

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