title: How to inject URL query string parameters in Python?
body: <p>I want to compose an equivalent debug URL for any URL of my organization's website. I have Python function to do this:</p>
  
  <pre><code>import urlparse
  import urllib
  
  def compose_debug_url(input_url):
      input_url_parts = urlparse.urlsplit(input_url)
      input_query = input_url_parts.query
      input_query_dict = urlparse.parse_qs(input_query)
  
      modified_query_dict = dict(input_query_dict.items() + [('debug', 'sp')])
      modified_query = urllib.urlencode(modified_query_dict)
      modified_url_parts = (
        input_url_parts.scheme,
        input_url_parts.netloc,
        input_url_parts.path,
        modified_query,
        input_url_parts.fragment
      )
  
      modified_url = urlparse.urlunsplit(modified_url_parts)
  
      return modified_url
  
  
  
  print compose_debug_url('http://www.example.com/content/page?name=john&amp;age=35')
  print compose_debug_url('http://www.example.com/')
  </code></pre>
  
  <p>If you run the code above, you should see the output:</p>
  
  <pre><code>http://www.example.com/content/page?debug=sp&amp;age=%5B%2735%27%5D&amp;name=%5B%27john%27%5D
  http://www.example.com/?debug=sp
  </code></pre>
  
  <p>Instead I expect:</p>
  
  <pre><code>http://www.example.com/content/page?debug=sp&amp;age=35&amp;name=john
  http://www.example.com/?debug=sp
  </code></pre>
  
  <p>It's because <code>urlparse.parse_qs</code> returns a dict of strings to lists rather than a dict of strings to strings.</p>
  
  <p>Is there another way to do this in Python more simply?</p>