问题:如何在Python中将字典转换为查询字符串?

使用后cgi.parse_qs(),如何将结果(字典)转换回查询字符串?寻找类似的东西 urllib.urlencode()

After using cgi.parse_qs(), how to convert the result (dictionary) back to query string? Looking for something similar to urllib.urlencode().


回答 0

Python 3

urllib.parse.urlencode(查询,doseq = False,[…])

映射对象或可能包含str或bytes对象的两个元素的元组序列转换百分比编码的ASCII文本字符串。

Python的3 urllib.parse文档

A dict是一个映射。

旧版Python

urllib.urlencodequery[,doseq])
映射对象或由两个元素组成的元组序列转换 “百分比编码”字符串…一系列key=value'&'字符分隔的对…

Python 2.7版urllib文档

Python 3

urllib.parse.urlencode(query, doseq=False, [...])

Convert a mapping object or a sequence of two-element tuples, which may contain str or bytes objects, to a percent-encoded ASCII text string.

Python 3 urllib.parse docs

A dict is a mapping.

Legacy Python

urllib.urlencode(query[, doseq])
Convert a mapping object or a sequence of two-element tuples to a “percent-encoded” string… a series of key=value pairs separated by '&' characters…

Python 2.7 urllib docs


回答 1

在python3中,略有不同:

from urllib.parse import urlencode
urlencode({'pram1': 'foo', 'param2': 'bar'})

输出: 'pram1=foo&param2=bar'

为了实现python2和python3的兼容性,请尝试以下操作:

try:
    #python2
    from urllib import urlencode
except ImportError:
    #python3
    from urllib.parse import urlencode

In python3, slightly different:

from urllib.parse import urlencode
urlencode({'pram1': 'foo', 'param2': 'bar'})

output: 'pram1=foo&param2=bar'

for python2 and python3 compatibility, try this:

try:
    #python2
    from urllib import urlencode
except ImportError:
    #python3
    from urllib.parse import urlencode

回答 2

您正在寻找完全一样的东西urllib.urlencode()

但是,当您调用parse_qs()(与区别parse_qsl())时,字典键是唯一的查询变量名称,而值是每个名称的值列表

为了将此信息传递到中urllib.urlencode(),您必须“展平”这些列表。这是使用元组列表理解的方法:

query_pairs = [(k,v) for k,vlist in d.iteritems() for v in vlist]
urllib.urlencode(query_pairs)

You’re looking for something exactly like urllib.urlencode()!

However, when you call parse_qs() (distinct from parse_qsl()), the dictionary keys are the unique query variable names and the values are lists of values for each name.

In order to pass this information into urllib.urlencode(), you must “flatten” these lists. Here is how you can do it with a list comprehenshion of tuples:

query_pairs = [(k,v) for k,vlist in d.iteritems() for v in vlist]
urllib.urlencode(query_pairs)

回答 3

也许您正在寻找这样的东西:

def dictToQuery(d):
  query = ''
  for key in d.keys():
    query += str(key) + '=' + str(d[key]) + "&"
  return query

它需要一个字典并将其转换为查询字符串,就像urlencode一样。它将在查询字符串后附加一个最终的“&”,但return query[:-1]如果有问题,则将其修复。

Maybe you’re looking for something like this:

def dictToQuery(d):
  query = ''
  for key in d.keys():
    query += str(key) + '=' + str(d[key]) + "&"
  return query

It takes a dictionary and convert it to a query string, just like urlencode. It’ll append a final “&” to the query string, but return query[:-1] fixes that, if it’s an issue.


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