Sling Academy
Home/Python/Python: How to Convert a Dictionary to a Query String

Python: How to Convert a Dictionary to a Query String

Last updated: February 12, 2024

What is a Query String?

A query string is a part of a URL that follows the ? symbol and contains key-value pairs separated by & symbols. It is used to pass data to a web server as parameters. The query string consists of parameter names and their corresponding values.

An example of a URL with a query string:

https://www.slingacademy.com/search?q=python&category=tutorials&page=1

In this example, the query string starts with the ? symbol and contains three key-value pairs: q=python, category=tutorials, and page=1. Each key-value pair is separated by &. The values in the query string are URL-encoded, which means special characters are replaced with their corresponding percent-encoded values. The web server can parse the query string to extract the parameters and use them for processing the request.

This concise, example-based article will walk you through a couple of different ways to convert a dictionary into a query string in Python. Without any further ado, let’s get started.

2 Ways to Convert a Dictionary to a Query String

Using urllib.parse.urlencode()

You can use the urllib.parse.urlencode() function from the urllib.parse module to encode the dictionary into a query string. This approach is simple and straightforward.

Example:

import urllib.parse

params = {"q": "python", "category": "tutorials", "page": 1}

# Encode the query string
query_string = urllib.parse.urlencode(params)

# Append the query string to the base URL
url = "https://www.slingacademy.com.com/search?" + query_string
print(url)

Output:

https://www.slingacademy.com.com/search?q=python&category=tutorials&page=1

Manual String Concatenation

An alternative solution is to iterate over the dictionary items and manually concatenate the key-value pairs into a query string. The step-by-step process is as follows:

  1. Create an empty list to store the key-value pairs.
  2. Iterate over the dictionary items using a loop.
  3. Encode each key-value pair and append it to the list.
  4. Join the list elements with & to form the query string.
  5. Append the query string to the base URL if necessary.

Code example:

params = {"q": "python", "category": "tutorials", "page": 1}

# Create an empty list to store key-value pairs
key_value_pairs = []

# Iterate over the dictionary items 
# and append encoded key-value pairs to the list
for key, value in params.items():
    key_value_pairs.append(f"{key}={value}")

# Join the list elements with "&" to form the query string
query_string = "&".join(key_value_pairs)

# Append the query string to the base URL
url = "https://www.slingacademy.com/search?" + query_string
print(url)

Output:

https://www.slingacademy.com/search?q=python&category=tutorials&page=1

This approach is more manual work and error-prone compared to using built-in functions.

Next Article: Python: Define Generic Types for Lists of Nested Dictionaries

Previous Article: 2 Ways to Create an Empty Tuple in Python

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs