📜  Python|键值到 URL 参数的转换

📅  最后修改于: 2022-05-13 01:55:02.444000             🧑  作者: Mango

Python|键值到 URL 参数的转换

很多时候,在 Web 开发领域工作时,我们可能会遇到一个问题,我们需要将我们拥有的一些键值对设置为 URL 参数,无论是元组的形式,还是键值列表的形式。让我们讨论这两种情况的解决方案。

方法 #1:使用urllib.urlencode() (使用元组)
urlencode函数是根函数,可以执行我们希望完成的任务。在元组的情况下,我们可以只传递元组,然后编码器完成字符串的其余转换。仅适用于 Python2。

# Python code to demonstrate working of
# Key-Value to URL Parameter Conversion
# Using urllib.urlencode() ( with tuples )
import urllib
  
# initializing tuples
test_tuples = (('Gfg', 1), ('is', 2), ('best', 3))
  
# printing original tuples
print("The original tuples are : " + str(test_tuples))
  
# Using urllib.urlencode() ( with tuples )
# Key-Value to URL Parameter Conversion
res = urllib.urlencode(test_tuples)
  
# printing URL string
print("The URL parameter string is : " + str(res))
输出 :
The original tuples are : (('Gfg', 1), ('is', 2), ('best', 3))
The URL parameter string is : Gfg=1&is=2&best=3

方法#2:使用urllib.urlencode() (带有字典值列表)
这种方法是当我们有一个字典键和许多与其对应的值作为 URL 参数的潜在候选者时。在这种情况下,我们执行此函数。这也仅适用于 Python2。

# Python code to demonstrate working of
# Key-Value to URL Parameter Conversion
# Using urllib.urlencode() ( with dictionary value list )
import urllib
  
# initializing dictionary
test_dict = {'gfg' : [1, 2, 3]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using urllib.urlencode() ( with dictionary value list )
# Key-Value to URL Parameter Conversion
res = urllib.urlencode(test_dict, doseq = True)
  
# printing URL string
print("The URL parameter string is : " + str(res))
输出 :
The original dictionary is : {'gfg': [1, 2, 3]}
The URL parameter string is : gfg=1&gfg=2&gfg=3