Python urlencode & OrderedDict
-
-
- 一、简单使用场景
- 二、复杂使用场景
- 三、小结
-
将一个mapping对象或两个元素元组的序列(序列可能包含str或bytes对象)转换为百分比编码的ASCII文本字符串。如果结果字符串要用作通过urlopen()函数进行POST操作的数据,则应将其编码为字节,否则将导致TypeError。
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. If the resultant string is to be used as a data for POST operation with the urlopen() function, then it should be encoded to bytes, otherwise it would result in a TypeError.
一、简单使用场景
from urllib.parse import urlencode
data = {
"name": "Allan","job": "Test development","token": "1234567890"
}
print(urlencode(data))
结果:name=Allan&job=Test+development&token=1234567890
二、复杂使用场景
先用OrderdDict对字典的key排序,然后再使用。
from urllib.parse import urlencode
data = {
"name": "Allan","job": "Test development","token": "1234567890"
}
print(urlencode(OrderedDict(sorted(data.items(), key=lambda t: t[0]))))
结果:job=Test+development&name=Allan&token=1234567890
三、小结
urlencode结合OrderedDict实现复杂实现,针对key或者value排序。