深度阅读

how to construct a URL from a dictionary in Python

作者
作者
2023年08月22日
更新时间
7.64 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。