0

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!

se_dude
  • 81
  • 1
  • 8
  • I guess the people marking this as duplicate aren't bothering to read the actual post. I know HOW to encode the URL, I am asking about the MOST EFFICIENT way of converting an array/list to the format urllib requires. Considering NONE of the results answer my specific question, I don't understand why you bothered marking this as duplicate. – se_dude Mar 14 '13 at 13:59

2 Answers2

2

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'
dm03514
  • 54,664
  • 18
  • 108
  • 145
2

You could use split('&') to break up the variables, and then loop through the resulting list and use split('=') to break up each variable and it's individual value, and then insert those values into an empty dictionary. Something like:

myDataString = "var1=value1&var2=value2&var3=value3"
mySplitData = myDataString.split('&')

import collections
myDict = collections.defaultdict(list)

for value in mySplitData:
    splitValue = value.split('=')
    myDict[splitValue[0]]

Note that this is untested code, I'll test this and get back to you.

Edit: Tested & updated the code.

Murkantilism
  • 1,060
  • 1
  • 16
  • 31
  • Thank you for taking the time to write/test code. It is a simple topic, but the way I had originally done this was a lot less efficient. – se_dude Mar 14 '13 at 15:28
  • No problem, glad I could help. I'm not sure if my solution or dm03514's fits your needs better, but don't forget to mark one of them as the answer =) – Murkantilism Mar 14 '13 at 15:35