用Python构建包含URL的字典的正确方法

用Python构建包含URL的字典的正确方法,python,Python,我试图查询一个API,在这里我需要填写零件号和制造商 假设我需要填写零件号为bav99,NXP Semiconductors为制造商。最终结果应如下所示: https://app.datafireball.com/SearchService/search/listPartSearch? partNumber=[{ %22partNumber%22:%22bav99wt%22, %22manufacturer%22:%22NXP%20Semiconductors%22}]& fmt=xml

我试图查询一个API,在这里我需要填写零件号和制造商

假设我需要填写零件号为bav99,NXP Semiconductors为制造商。最终结果应如下所示:

https://app.datafireball.com/SearchService/search/listPartSearch?
partNumber=[{
%22partNumber%22:%22bav99wt%22,
%22manufacturer%22:%22NXP%20Semiconductors%22}]&
fmt=xml
我不得不说,我真的很困惑,哪些字符应该编码,哪些不应该。根据我所看到的,双引号应编码为%22,空格应编码为%20

我所做的:

import urllib
urltemplate = """https://app.datafireball.com/SearchService/search/listPartSearch?partNumber=[{{%22partNumber%22:%22{0}%22,%22manufacturer%22:%22{1}%22}}]&fmt=xml"""
# I have to recode the curly brackets to be double curly brackets, otherwise place holder won't work.
url = urltemplate.format(urllib.quote('my partnumber'), urllib.quote('my manufacturer') )
print url
我想我可以把我的担忧概括为以下两个问题:

为什么某些字符应该被编码,而有些不应该

什么是正确的方法和实用的方法来编码的对象,而不是使用占位符硬编码它

这对你有帮助吗

urllib.urlencodequery[,doseq]^

Convert a mapping object or a sequence of two-element tuples 
to a “percent-encoded” string, suitable to pass to urlopen() above as the
optional data argument. This is useful to pass a dictionary of form
fields to a POST request.