title: Finding a key recursively in a dictionary
body: <p>I'm trying to write a very simple function to recursively search through a possibly nested (in the most extreme cases ten levels deep) Python dictionary and return the first value it finds from the given key.</p>
  <p>I cannot understand why my code doesn't work for nested dictionaries.</p>
  <pre><code>def _finditem(obj, key):
      if key in obj: return obj[key]
      for k, v in obj.items():
          if isinstance(v,dict):
              _finditem(v, key)
  
  print _finditem({&quot;B&quot;:{&quot;A&quot;:2}},&quot;A&quot;)
  </code></pre>
  <p>It returns <code>None</code>.</p>
  <p>It does work, however, for <code>_finditem({&quot;B&quot;:1,&quot;A&quot;:2},&quot;A&quot;)</code>, returning <code>2</code>.</p>
  <p>I'm sure it's a simple mistake but I cannot find it. I feel like there already might be something for this in the standard library or <code>collections</code>, but I can't find that either.</p>
  <hr />
  <p><sub>If you are looking for a general explanation of what is wrong with code like this, the canonical is <a href="https://stackoverflow.com/questions/17778372">Why does my recursive function return None?</a>. The answers here are mostly specific to the task of searching in a nested dictionary.</sub></p>