Most efficient way of sending a string with multiple variables as POST data using urllib
Question: I feel really dumb for having to post this, but I am brand new to Python, and
it isn't anything like PHP, which I do know.

I have a string of data, which contains 1 or more variables, example:

    
    
    "var1=value1&var2=value2&var3=value3"
    

I need to send this data to a web server using POST, using urllib.

I have no problems manually formatting the POST data, and send it, but I am
having trouble figuring out how to do this with code, without having to write
complex code.

It's pretty easy to use split('&') to change this string into an array, but
then what?

It looks like I need convert the data to the following syntax before I can
urllib.urlencode it:

    
    
    {"var1":"value1","var2":"value2","var3":"value3"}
    

Any suggestions would be greatly appreciated!


Answer: Python has functions for most operations you will have to do with
querystrings/urls. You can turn your string into a dict (like below)

    
    
    Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> qs = "var1=value1&var2=value2&var3=value3"
    >>> from urlparse import parse_qs
    >>> parse_qs(qs)
    {'var1': ['value1'], 'var3': ['value3'], 'var2': ['value2']}
    >>> data_dict = parse_qs(qs)      
    >>> import urllib
    >>> post_data_str = urllib.urlencode(data_dict)
    >>> post_data_str
    'var1=%5B%27value1%27%5D&var3=%5B%27value3%27%5D&var2=%5B%27value2%27%5D'
    

