Open In App

How to Change a Django QueryDict to Python Dict

Last Updated : 16 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Django, a QueryDict is a specialized dictionary that handles HTTP GET and POST parameters. In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict.

There are instances when we may need to convert the QueryDict into a regular Python dictionary dict() to perform various operations. QueryDict is a subclass of dictionary, so it uses all the standard dictionary methods.

Using dict() Function

We can use the dict() function to convert the QueryDict into Python native data type. Each key in QueryDict contains a list with one or more values.

>>> from django.http import QueryDict

>>> query_dict = QueryDict('studentName=Marya&age=26&languages=Python&
languages=JavaScript&courses=DataScience&courses=WebDevelopment')

>>> query_dict

<QueryDict: {'studentName': ['Marya'], 'age': ['26'], 'languages': ['Python', 'JavaScript'],
'courses': ['DataScience', 'WebDevelopment']}>

Convert QueryDict to Python Dictionary

>>> data = dict(query_dict)

>>> data
{'studentName': ['Marya'], 'age': ['26'], 'languages': ['Python', 'JavaScript'], 'courses': ['DataScience', 'WebDevelopment']}

The only problem here is that each key has a list as a value. We can use querydict.dict() method to get {key:value} pairs:

>>> data = query_dict.dict()         
>>> data
{'studentName': 'Marya', 'age': '26', 'languages': 'JavaScript', 'courses': 'WebDevelopment'}

There are few things we need to know before converting a QueryDict to Python dict:

  • QueryDict.get(key) : This function returns a value of the key we are at or the provided key, and if there are multiple values present in the given key then it returns the last value of that key. Example : dict_one : {'name' : 'Rahul', 'age' : '30', 'language_knows' : [ 'java', 'python', 'C++' ] }, then it returns only 'C++' for they key 'language_knows' key.
  • QueryDict.getlist(key): This function return the list of values for the given key, means if there are more than one values present for a particular key than returns all of them instead of single value. from the above example it returns all the value [ 'java', 'python', 'C++' ] for the key 'language_knows'.

Example 1: Accessing QueryDict Values

Python
from django.http import QueryDict

# Create a QueryDict
query_Dict = QueryDict(
  'studentName=Marya&age=26&languages=Python&languages=JavaScript&courses=DataScience&courses=WebDevelopment'
)

# Convert into a regular dictionary with single values
regularDict = query_Dict.dict()
print(regularDict)

# Convert to a regular dictionary with lists of values
regularDict_lists = {key: query_Dict.getlist(key) for key in query_Dict.keys()}
print(regularDict_lists)

# Accessing QueryDict values directly

#accessing Name of the student only
student_name = query_Dict.get('studentName')
print(student_name)

# accessing list of languages student knows
languages = query_Dict.getlist('languages')
print(languages)

# accessing the list of courses student opt for 
courses = query_Dict.getlist('courses')
print(courses)

Output:

for single value of each key
{'studentName': 'Marya', 'age': '26', 'languages': 'JavaScript', 'courses': 'WebDevelopment'}

output of multiple values for each key if any
{'studentName': ['Marya'], 'age': ['26'], 'languages': ['Python', 'JavaScript'] , 'courses': ['DataScience', 'WebDevelopment']}

Accessing single key and their values
Marya

Accessing list of the Values for a particular key
['Python', 'JavaScript']

['DataScience', 'WebDevelopment']

Explanation:

In the above code let's see step by step what we did

  • First we import "from django.http import QueryDict" in python used to bring 'QueryDict' class form Django 'http' module. when we get the HTTP request while filling a form from user this helps to handle and manipulate the data that have multiple values for single key.
  • Then in query_dict the dictionary is stored or we can say the data we get form the user is storing with keys student Name, age, languages and courses
  • First convert the 'QueryDict' to a regular dictionary using 'query_Dict.dict()'. in a variable called regular_dict, Note that this conversion will only keep the last value for each key if there are multiple values. Therefore, 'languages' have 'javascript' and 'courses' have 'webDevelopment' only.
  • query_Dict.getlist(key) : this method retrieves all values associated with a given key form the QueryDict as a list. If there present the multiple values in the key then all values are included in the list and if single value the list will contain only that.
  • query_Dict.keys(): This method returns an iterable of all keys present in the QueryDict.
  • {key: query_Dict.getlist(key) for key in query_Dict.keys()}: So this has to function like it iterates over each keys in 'query_Dict' for each key it uses.
  • query_Dict.getlist(key) : it is to fetch all associated values as a list. The resulting key-value pairs are then assembled into a new dictionary, regularDict_lists.
  • This is the output we get for keys having multiple values languages : ['Python', 'JavaScript'], and courses : ['DataScience', 'WebDevelopment'].

Accessing QueryDict Values Directly

  • query_dict.get('studentName') will return only the name of the student.(a single value)
  • query_dict.getlist('languages') will return only the languages list she knows or studying.(multiple values)
  • query_dict.getlist('courses') will return only the list of courses she took.(multiple values or list of values in a key).

Example 2: Converting a Post QueryDict to a Dict

Python
from django.http import HttpRequest

# mimic a POST request with data
request = HttpRequest()
request.method = 'POST'
request.POST = QueryDict('username=marya&password=itspass&age=29')

# Convert request.POST to a regular dictionary
post_data_dict = request.POST.dict()
print(post_data_dict)

Output:

{'username': 'marya', 'password': 'itspass', 'age': '29'}

Explanation:

  • from django.http import HttpRequest: a httprequest class is imported from django http module. It works as container that holds all the information about the web request made to a django application.
  • request = HttpRequest() : request is created to store some details which is coming from the httpRequest() that is an instance of class 'HttpRequest'.
  • request.method = 'POST' : in this line the method is set to POST for request. 'POST' means it's a type of request where data is being sent to the server, typically when a user submits a form.
  • request.POST = QueryDict('username=marya&password=itspass&age=29'): this line creates a QueryDict, a special kind of dictionary designed to handle form data in Django.
  • post_data_dict = request.POST.dict() : in this line a QueryDict is converted into a regular Dictionary using dict() and then store the new Dictionary into a post_data_dict.
  • print(post_data_dict): this line will print the output of regular dictionary.

Example3: Using Dictionary Comprehension

This is another way of solving the above same example with little change in the function of regularDict which is explained below.

Python
from django.http import QueryDict

queryDict = QueryDict(
  'student=Marya&age=29&languages=Python&languages=JavaScript&courses=DataScience&courses=WebDevelopment'
)

regularDict = {
    key: queryDict.getlist(key) if len(queryDict.getlist(key)) > 1 else queryDict.get(key)
    for key in queryDict.keys()
}
print(regularDict)


Output:

 {'student': 'Marya', 'age': '29', 'languages': ['Python', 'JavaScript'], 'courses': ['DataScience', 'WebDevelopment']}

Explanation:

  • First iterate over all the keys present in the dictionary.
  • Condition: It checks if there is more than one value associated with each key using len(query_dict.getlist(key)) > 1.
  • If there present more than one value of any key then query_dict.getlist(key) will returns a list of those values.
  • If present a single value for any key then query_dict.get(key) will returns that single value.

So, student and age having single value so they are stored as individuals in the resulting dictionary and languages and courses consists of list of values so they stored as a list in resulting dict.

It is the efficient way and readable for simple conversation, and this approach achieves the same result but in a more concise form using dictionary comprehension.

Conclusion:

Using dict() is a direct and simple way of converting a django QueryDict into a regular python dictionary. With these techniques, we can efficiently handle and transform QueryDict objects to suit your needs.


Next Article
Article Tags :
Practice Tags :

Similar Reads