how to construct a URL from a dictionary in Python
Published on Aug. 22, 2023, 12:15 p.m.
Here’s how to construct a URL from a dictionary in Python:
To construct a URL from a dictionary in Python, you can use the urllib.parse.urlencode()
function. This function encodes the dictionary as a query string and appends it to the base URL. Here’s an example:
from urllib.parse import urlencode
base_url = 'https://www.example.com/search'
params = {'q': 'python tutorial', 'page': 2}
url = base_url + '?' + urlencode(params)
print(url)
In this example, we start with a base URL (https://www.example.com/search
) and a dictionary of parameters ('q': 'python tutorial', 'page': 2
). We then use the urlencode()
function to encode the parameters as a query string and append it to the base URL. The resulting URL is printed to the console.