Keeping url parameters in order when encoding with urllib

依然范特西╮ 提交于 2019-12-11 02:43:50

问题


I am trying to simulate a get request with python. I have a dictionary of parameters and am using urllib.urlencode to urlencode them

I notice that although the dictionary is of the form:

{ "k1":"v1", "k2":"v2", "k3":"v3", .. }

upon urlencoding the order of the parameters is switched to:

/?k1=v1&k3=v3%k2=v2...

why does this happen and can I force the order in the dictionary to stay the same?


回答1:


As you can see in the comments, Python dictionaries are not ordered, but there is an OrderedDict in Python that you can use to achieve the result you want:

from collections import OrderedDict
import urllib
urllib.urlencode(OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]))
# Out: 'k1=v1&k2=v2&k3=v3'

More info about OrderedDIct



来源:https://stackoverflow.com/questions/25107663/keeping-url-parameters-in-order-when-encoding-with-urllib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!