使用urllib进行编码时,请保持url参数的顺序 [英] Keeping url parameters in order when encoding with urllib

查看:254
本文介绍了使用urllib进行编码时,请保持url参数的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用python来模拟一个get请求。我有一个参数字典,并且使用urllib.urlencode来对它们进行编码。



我注意到尽管字典有以下形式:

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

对于urlencoding,参数的顺序切换到:

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

为什么会发生这种情况,我可以强制字典中的顺序保持不变吗?

解决方案

正如你所见评论,Python字典没有订购,但在Python中有一个 OrderedDict ,您可以使用它们来实现所需的结果:

 从集合导入OrderedDict 
import urllib
urllib.urlencode(OrderedDict([('k1','v1'),('k2' 'v2'),('k3','v3')]))
#Out:'k1 = v1& k2 = v2& k3 = v3'
pre>

有关 OrderedDIct


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?

解决方案

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

这篇关于使用urllib进行编码时,请保持url参数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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