Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Python parse_qs from parsing single values into lists?

In python 2.6, the following code:

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

Gives the following output:

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

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']} 
like image 950
Shabbyrobe Avatar asked Jun 21 '09 15:06

Shabbyrobe


2 Answers

A sidenote for someone just wanting a simple dictionary and never needing multiple values with the same key, try:

dict(urlparse.parse_qsl('foo=bar&baz=qux')) 

This will give you a nice {'foo': 'bar', 'baz': 'qux'}. Please note that if there are multiple values for the same key, you'll only get the last one.

like image 53
tuomassalo Avatar answered Sep 20 '22 13:09

tuomassalo


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.

like image 35
SingleNegationElimination Avatar answered Sep 21 '22 13:09

SingleNegationElimination