How to change a django QueryDict to Python Dict?
Let's pretend I have the following QueryDict:
<QueryDict: {u'num': [0], u'var1': [u'value1', u'value2'], u'var2': [u'8']}>
I'd like to have a dictionary out of this, eg:
{'num': [0], 'var1':['value1', 'value2'], 'var2':['8']}
(I don't care if the unicode symbol u
stays or goes.)
If I do queryDict.dict()
, as suggested by the django site, I lose the extra values belonging to var1
, eg:
{'num': [0], 'var1':['value2'], 'var2':['8']}
I was thinking of doing this:
myDict = {}
for key in queryDict.iterkeys():
myDict[key] = queryDict.getlist(key)
Is there a better way?
Solution 1:
New in Django >= 1.4.
QueryDict.dict()
https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.QueryDict.dict
Solution 2:
This should work: myDict = dict(queryDict.iterlists())
Solution 3:
This is what I've ended up using:
def qdict_to_dict(qdict):
"""Convert a Django QueryDict to a Python dict.
Single-value fields are put in directly, and for multi-value fields, a list
of all values is stored at the field's key.
"""
return {k: v[0] if len(v) == 1 else v for k, v in qdict.lists()}
From my usage this seems to get you a list you can send back to e.g. a form constructor.
EDIT: maybe this isn't the best method. It seems if you want to e.g. write QueryDict
to a file for whatever crazy reason, QueryDict.urlencode()
is the way to go. To reconstruct the QueryDict
you simply do QueryDict(urlencoded_data)
.
Solution 4:
from django.utils import six
post_dict = dict(six.iterlists(request.POST))