Search code examples
pythonformencode

Transform a python dict into string compatible with Content-Type:"application/x-www-form-urlencoded"


I'd like to take a python dict object and transform it into its equivalent string if it were to be submitted as html form data.

The dict looks like this:

{
   'v_1_name':'v_1_value'
  ,'v_2_name':'v_2_value'
}

I believe the form string should look something like this:

v_1_name=v_1_value&v_2_name=v_2_value

What is a good way to do this?

Thanks!


Solution

  • Try urllib.parse.urlencode:

    >>> from urllib.parse import urlencode
    >>> urlencode({'foo': 1, 'bar': 2})
    'foo=1&bar=2'