Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

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 jezdez authored
6 django/utils/datastructures.py
View
@@ -391,6 +391,12 @@ def update(self, *args, **kwargs):
for key, value in kwargs.iteritems():
self.setlistdefault(key, []).append(value)
+ def dict(self):
+ """
+ Returns current object as a dict with singular values.
+ """
+ return dict((key, self[key]) for key in self)
+
class DotExpandedDict(dict):
"""
A special dictionary constructor that takes a dictionary in which the keys
12 docs/ref/request-response.txt
View
@@ -482,6 +482,18 @@ In addition, ``QueryDict`` has the following methods:
>>> q.lists()
[(u'a', [u'1', u'2', u'3'])]
+.. method:: QueryDict.dict()
+
+ .. versionadded:: 1.4
+
+ Returns ``dict`` representation of ``QueryDict``. For every (key, list)
+ pair in ``QueryDict``, ``dict`` will have (key, item), where item is one
+ element of the list, using same logic as :meth:`QueryDict.__getitem__()`::
+
+ >>> q = QueryDict('a=1&a=3&a=5')
+ >>> q.dict()
+ {u'a': u'5'}
+
.. method:: QueryDict.urlencode([safe])
Returns a string of the data in query-string format. Example::
12 tests/regressiontests/utils/datastructures.py
View
@@ -235,6 +235,18 @@ def test_copy(self):
self.assertEqual(d1["key"], ["Penguin"])
self.assertEqual(d2["key"], ["Penguin"])
+ def test_dict_translation(self):
+ mvd = MultiValueDict({
+ 'devs': ['Bob', 'Joe'],
+ 'pm': ['Rory'],
+ })
+ d = mvd.dict()
+ self.assertEqual(d.keys(), mvd.keys())
+ for key in mvd.keys():
+ self.assertEqual(d[key], mvd[key])
+
+ self.assertEqual({}, MultiValueDict().dict())
+
class DotExpandedDictTests(DatastructuresTestCase):
Please sign in to comment.
Something went wrong with that request. Please try again.