Python字典到网址参数 [英] Python Dictionary to URL Parameters

查看:124
本文介绍了Python字典到网址参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Python字典转换为用作URL参数的字符串。我相信,这样做有一个更好的 Pythonic 的方式。这是什么?

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]


推荐答案

使用 urllib.urlencode() 。它需要键值对的字典,并将其转换为适合于URL的格式(例如, key1 = val1& key2 = val2 )。

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

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

如果你想做一个URL重复参数如: p = 1& p = 2& p = 3 您有两个选项:

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'

或者如果您想要重复参数的URL:

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'

这篇关于Python字典到网址参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆