如何阻止 Python parse_qs 将单个值解析为列表? [英] How to stop Python parse_qs from parsing single values into lists?

查看:104
本文介绍了如何阻止 Python parse_qs 将单个值解析为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python 2.6中,代码如下:

In python 2.6, the following code:

import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = urlparse.parse_qs(qsdata)
print qs

给出以下输出:

{'test': ['test'], 'test2': ['test2', 'test3']}

这意味着即使只有一个 test 值,它仍然被解析成一个列表.有没有办法确保如果只有一个值,它不会被解析成一个列表,从而使结果看起来像这样?

Which means that even though there is only one value for test, it is still being parsed into a list. Is there a way to ensure that if there's only one value, it is not parsed into a list, so that the result would look like this?

{'test': 'test', 'test2': ['test2', 'test3']}

推荐答案

你可以稍后修复它...

You could fix it afterwards...

import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = dict( (k, v if len(v)>1 else v[0] ) 
           for k, v in urlparse.parse_qs(qsdata).iteritems() )
print qs

但是,我不认为会想要这个.如果一个通常是列表的参数碰巧只包含一个项目集,那么我会得到一个字符串,而不是我通常收到的字符串列表.

However, I don't think I would want this. If a parameter that is normally a list happens to arrive with only one item set, then I would have a string instead of the list of strings I normally receive.

这篇关于如何阻止 Python parse_qs 将单个值解析为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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