问题:Python字典到URL参数

我正在尝试将Python字典转换为用作URL参数的字符串。我敢肯定,有一种更好的,更Python化的方法可以做到这一点。它是什么?

x = ""
for key, val in {'a':'A', 'b':'B'}.items():
    x += "%s=%s&" %(key,val)
x = x[:-1]

I am trying to convert a Python dictionary to a string for use as URL parameters. I am sure that there is a better, more Pythonic way of doing this. What is it?

x = ""
for key, val in {'a':'A', 'b':'B'}.items():
    x += "%s=%s&" %(key,val)
x = x[:-1]

回答 0

使用。它采用键值对字典,然后将其转换为适合网址的形式(例如,key1=val1&key2=val2)。

如果您使用的是Python3,请使用 urllib.parse.urlencode()

如果要使用重复的参数创建URL,例如:p=1&p=2&p=3您有两个选择:

>>> import urllib
>>> a = (('p',1),('p',2), ('p', 3))
>>> urllib.urlencode(a)
'p=1&p=2&p=3'

或者,如果您想使用重复的参数创建网址:

>>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True)
'p=1&p=2&p=3'

Use . It takes a dictionary of key-value pairs, and converts it into a form suitable for a URL (e.g., key1=val1&key2=val2).

If you are using Python3, use urllib.parse.urlencode()

If you want to make a URL with repetitive params such as: p=1&p=2&p=3 you have two options:

>>> import urllib
>>> a = (('p',1),('p',2), ('p', 3))
>>> urllib.urlencode(a)
'p=1&p=2&p=3'

or if you want to make a url with repetitive params:

>>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True)
'p=1&p=2&p=3'

回答 1

使用第三方Python URL操作库furl

f = furl.furl('')
f.args = {'a':'A', 'b':'B'}
print(f.url) # prints ... '?a=A&b=B'

如果需要重复的参数,可以执行以下操作:

f = furl.furl('')
f.args = [('a', 'A'), ('b', 'B'),('b', 'B2')]
print(f.url) # prints ... '?a=A&b=B&b=B2'

Use the 3rd party Python url manipulation library furl:

f = furl.furl('')
f.args = {'a':'A', 'b':'B'}
print(f.url) # prints ... '?a=A&b=B'

If you want repetitive parameters, you can do the following:

f = furl.furl('')
f.args = [('a', 'A'), ('b', 'B'),('b', 'B2')]
print(f.url) # prints ... '?a=A&b=B&b=B2'

回答 2

在我看来,这似乎更像Pythonic,并且不使用任何其他模块:

x = '&'.join(["{}={}".format(k, v) for k, v in {'a':'A', 'b':'B'}.items()])

This seems a bit more Pythonic to me, and doesn’t use any other modules:

x = '&'.join(["{}={}".format(k, v) for k, v in {'a':'A', 'b':'B'}.items()])

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。