title: Python: Convert complex dictionary of strings from Unicode to ASCII
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-unicode-ones-from-json-in-python">How to get string Objects instead Unicode ones from JSON in Python?</a>  </p>
  </blockquote>
  
  
  
  <p>I have a lot of input as multi-level dictionaries parsed from JSON API calls. The strings are all in unicode which means there is a lot of <code>u'stuff like this'</code>. I am using <a href="http://stedolan.github.com/jq/" rel="nofollow noreferrer">jq</a> to play around with the results and need to convert these results to ASCII.</p>
  
  <p>I know I can write a function to just convert it like that:</p>
  
  <pre><code>def convert(input):
      if isinstance(input, dict):
          ret = {}
          for stuff in input:
              ret = convert(stuff)
      elif isinstance(input, list):
          ret = []
          for i in range(len(input))
              ret = convert(input[i])
      elif isinstance(input, str):
          ret = input.encode('ascii')
      elif :
          ret = input
      return ret
  </code></pre>
  
  <p>Is this even correct? Not sure. That's not what I want to ask you though.</p>
  
  <p>What I'm asking is, this is a typical brute-force solution to the problem. There must be a better way. A more pythonic way. I'm no expert on algorithms, but this one doesn't look particularly fast either.</p>
  
  <p>So is there a better way? Or if not, can this function be improved...?</p>
  
  <hr>
  
  <p><strong>Post-answer edit</strong></p>
  
  <p><a href="https://stackoverflow.com/a/13101776/677139">Mark Amery's answer</a> is correct but I would like to post a modified version of it. His function works on Python 2.7+ and I'm on 2.6 so had to convert it:</p>
  
  <pre><code>def convert(input):
      if isinstance(input, dict):
          return dict((convert(key), convert(value)) for key, value in input.iteritems())
      elif isinstance(input, list):
          return [convert(element) for element in input]
      elif isinstance(input, unicode):
          return input.encode('utf-8')
      else:
          return input
  </code></pre>