Django: Can I create a QueryDict from a dictionary?

Imagine that I have a dictionary in my Django application:

dict = {'a': 'one', 'b': 'two', }

Now I want to easily create an urlencoded list of GET parameters from this dictionary. Of course I could loop through the dictionary, urlencode keys and values and then concatenate the string by myself, but there must be an easier way. I would like to use a QueryDict instance. QueryDict is a subclass of dict, so it should be possible somehow.

qdict = QueryDict(dict) # this does not actually work
print qdict.urlencode()

How would I make the second to last line work?


How about?

from django.http import QueryDict

ordinary_dict = {'a': 'one', 'b': 'two', }
query_dict = QueryDict('', mutable=True)
query_dict.update(ordinary_dict)

Python has a built in tool for encoding a dictionary (any mapping object) into a query string

params = {'a': 'one', 'b': 'two', }

urllib.urlencode(params)

'a=one&b=two'

http://docs.python.org/2/library/urllib.html#urllib.urlencode

QueryDict takes a querystring as first param of its contstructor

def __init__(self, query_string, mutable=False, encoding=None):

q = QueryDict('a=1&b=2')

https://github.com/django/django/blob/master/django/http/request.py#L260

Update: in Python3, urlencode has moved to urllib.parse:

from urllib.parse import urlencode

params = {'a': 'one', 'b': 'two', }
urlencode(params)
'a=one&b=two'

Actually a little indirect but more logical way to achieve this is using MultiValueDict. This way multiple values per key can be stored in a QueryDict and .getlist method should then work fine.

from django.http.request import QueryDict, MultiValueDict
dictionary = {'my_age': ['23'], 'my_girlfriend_age': ['25', '27'], }

qdict = QueryDict('', mutable=True)
qdict.update(MultiValueDict(dictionary))

print qdict.get('my_age')  # 23
print qdict['my_girlfriend_age']  # 27
print qdict.getlist('my_girlfriend_age')  # ['25', '27']