title: What is the best (idiomatic) way to check the type of a Python variable?
body: <p>I need to know if a variable in Python is a string or a dict.  Is there anything wrong with the following code?</p>
  
  <pre><code>if type(x) == type(str()):
      do_something_with_a_string(x)
  elif type(x) == type(dict()):
      do_somethting_with_a_dict(x)
  else:
      raise ValueError
  </code></pre>
  
  <p><strong>Update</strong>: I accepted avisser's answer (though I will change my mind if someone explains why <code>isinstance</code> is preferred over <code>type(x) is</code>).</p>
  
  <p>But thanks to nakedfanatic for reminding me that it's often cleaner to use a dict (as a case statement) than an if/elif/else series.</p>
  
  <p>Let me elaborate on my use case.  If a variable is a string, I need to put it in a list.  If it's a dict, I need a list of the unique values.  Here's what I came up with:</p>
  
  <pre><code>def value_list(x):
      cases = {str: lambda t: [t],
               dict: lambda t: list(set(t.values()))}
      try:
          return cases[type(x)](x)
      except KeyError:
          return None
  </code></pre>
  
  <p>If <code>isinstance</code> is preferred, how would you write this <code>value_list()</code> function?</p>