Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a URL query string into a list of tuples using Python?

I am struggling to convert a url to a nested tuple.

# Convert this string
str = 'http://somesite.com/?foo=bar&key=val'

# to a tuple like this:
[(u'foo', u'bar'), (u'key', u'val')]

I assume I need to be doing something like:

 url = 'http://somesite.com/?foo=bar&key=val'
 url = url.split('?')
 get = ()
 for param in url[1].split('&'):
     get = get + param.split('=')

What am I doing wrong? Thanks!

like image 702
orwellian Avatar asked Aug 19 '09 21:08

orwellian


People also ask

How do you convert a string to a list of tuples?

When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

How do you convert a string to a tuple in Python?

Method #1 : Using map() + int + split() + tuple() This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple.

How do you convert a list of tuples to a list of strings in Python?

Method #1: Using list comprehension + join() The list comprehension performs the task of iterating the entire list of tuples and the join function performs the task of aggregating the elements of tuples into one list.

Which method can be used to convert a list to a tuple Python?

Inbuilt tuple() function, also known as a constructor function, can be used to convert a list to a tuple. We can use for loop inside the tuple function to convert the list into a tuple. It is faster to convert the list to a tuple in python by unpacking the list inside parenthesis.


1 Answers

I believe you are looking for the urlparse module.

This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.”

Here is an example:

from urlparse import urlparse, parse_qsl

url = 'http://somesite.com/?foo=bar&key=val'
print parse_qsl(urlparse(url)[4])

Output:

[('foo', 'bar'), ('key', 'val')]

In this example I first use the urlparse function to parse the entire URL then I use the parse_qsl function to break the querystring (the fifth element returned from urlparse) into a list of tuples.

like image 82
Andrew Hare Avatar answered Oct 20 '22 04:10

Andrew Hare