我想將Python字典轉換爲字符串作爲URL參數使用。我相信有更好的,更多的做法。它是什麼?Python字典到URL參數
x = ""
for key, val in {'a':'A', 'b':'B'}.items():
x += "%s=%s&" %(key,val)
x = x[:-1]
我想將Python字典轉換爲字符串作爲URL參數使用。我相信有更好的,更多的做法。它是什麼?Python字典到URL參數
x = ""
for key, val in {'a':'A', 'b':'B'}.items():
x += "%s=%s&" %(key,val)
x = x[:-1]
使用urllib.urlencode()
。它需要一個鍵值對的字典,並將其轉換爲適合URL的格式(例如,key1=val1&key2=val2
)。
如果您正在使用Python3,使用urllib.parse.urlencode()
如果你想與重複PARAMS如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'
,或者如果你想一個url與重複PARAMS:
>>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True)
'p=1&p=2&p=3'
參考:http://docs.python.org/library/urllib.html#urllib.urlencode – 2009-08-05 14:31:55
如果你想使用重複的參數,例如:?p = 1&p = 2&p = 3,然後a =((' p',1),('p',2),('p',3)); urllib.urlencode(a)結果爲'p = 1&p = 2&p = 3' – panchicore 2012-06-27 17:05:58
獲得重複參數的另一種方法:urllib.urlencode({'p':[1,2,3]},doseq = True) 'p = 1&p = 2&p = 3'。 – mbaechtold 2014-04-16 10:51:24
使用第三方Python的URL處理庫捲起:
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'
我在哪裏得到furl?它似乎不是標準庫 – 2017-03-27 20:34:24
'pip install furl'它不是標準庫的一部分 – 2017-04-04 11:41:17
這似乎更Python到我了一下,不使用任何其他模塊:
x = '&'.join(["{}={}".format(k, v) for k, v in {'a':'A', 'b':'B'}.items()])
這不會百分比正確地編碼參數。如果您的數據包含&符,等號,散列符號等,這將會產生意想不到的結果。 – 2017-05-22 10:26:08
Pythonic這個詞。應該給出相應的-1來表示該單詞的模糊性。 – TMB 2011-09-13 16:27:12