How to Change a Django QueryDict to Python Dict
Last Updated :
16 Aug, 2024
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.
Similar Reads
How to Convert a Django QuerySet to a List?
Converting a Django QuerySet to a list can be accomplished using various methods depending on your needs. Whether you want a list of model instances, specific fields, IDs, or serialized data, Django provides flexible ways to achieve this. Understanding these methods will help you effectively work wi
3 min read
How to check Django version
This article is for checking the version of Django. When we create projects using Django and sometimes we might stuck where the version is not able to support certain functions of your code. There are many methods to check the current version of Django but you need Django installed on your machine.
2 min read
How to Execute a Python Script from the Django Shell?
The Django shell is an interactive development and scripting environment that aids us in working with our Django project while experiencing it as if it were deployed already. It is most commonly used when one has to debug, test, or carry out one-time operations that require interaction with the Djan
4 min read
How to Output Django QuerySet as JSON
In Django, a common task for web developers is to return data in JSON format, especially when working with APIs. A Django QuerySet, which is a collection of database queries, can be serialized and output as JSON. This article will guide us through how to output a Django QuerySet as JSON using two me
4 min read
How To Convert Python Dictionary To JSON?
In Python, a dictionary stores information using key-value pairs. But if we want to save this data to a file, share it with others, or send it over the internet then we need to convert it into a format that computers can easily understand. JSON (JavaScript Object Notation) is a simple format used fo
7 min read
How to Add Data from Queryset into Templates in Django
In this article, we will read about how to add data from Queryset into Templates in Django Python. Data presentation logic is separated in Django MVT(Model View Templates) architecture. Django makes it easy to build web applications with dynamic content. One of the powerful features of Django is fet
3 min read
How to Query as GROUP BY in Django?
In Django, the powerful ORM (Object-Relational Mapping) allows developers to interact with databases using Python code. One common database operation is the GROUP BY query, which groups rows sharing a property so that aggregate functions can be applied to each group. This article will guide you thro
3 min read
How To Implement ChatGPT In Django
Integrating ChatGPT into a Django application allows you to create dynamic and interactive chat interfaces. By following the steps outlined in this article, you can implement ChatGPT in your Django project and provide users with engaging conversational experiences. Experiment with different prompts,
4 min read
How to convert Ordereddict to JSON?
In this article, we will learn How to convert a nested OrderedDict to JSON? Before this we must go through some concepts: The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the d
3 min read
How to convert JSON to Ordereddict?
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Pytho
2 min read