Reputation: 1248
I have this QueryDict:
>>> from django.http import QueryDict
>>> q = QueryDict('a=1&a=2&c=3')
I need a piece of code which returns this result:
{ u'a': [u'1',u'2'], u'c': u'3'}
I should inform you that dict(q.iterlists())
returns this:
{ u'a': [u'1', u'2'], u'c': [u'3']}
Regards,
Upvotes: 0
Views: 702
Reputation: 3100
Shorter answer:
{
key:val if len(val)>1 else val[0]
for key,val in q.lists()
}
Upvotes: 2
Reputation: 78760
I agree with the comments that you should not want this.
Anyway, this comprehension gets rid of the unicode strings (again, you should not want this) and single value lists:
d = { 'a': ['1', '2'], 'c': [u'3']}
>>> {k:(map(str, v) if len(v) > 1 else str(v[0])) for k,v in d.items()}
{'a': ['1', '2'], 'c': '3'}
Upvotes: 1
Reputation: 9235
If you want the querydict to be converted into json,
You could do something like this,
>>> from django.http import QueryDict
>>> q = QueryDict('a=1&a=2&c=3')
>>> q
<QueryDict: {'c': ['3'], 'a': ['1', '2']}>
I actually did it like this,
>>> string_dict = json.loads(json.dumps(dict(q)))
>>> string_dict
{'c': ['3'], 'a': ['1', '2']}
>>> for item in string_dict:
... if len(string_dict[item]) == 1:
... string_dict[item] = string_dict[item][0]
...
>>> string_dict
{'c': '3', 'a': ['1', '2']}
Upvotes: 1