title: Python algorithm to search keys and values
body: <p>Part of an algorithm course I am taking is to use look through a dictionary of keys and values and continue to look for matching keys &amp; values. For example if there is a matching key, use the value to look up the next key and continue down the rabbit hole. If a match if found more than once to prevent an infinite loop return False else it should return the last key found.</p>
  <ol>
  <li>Look up a key called &quot;bat&quot;, and find a value &quot;pig&quot; then continue</li>
  <li>Look up a key called &quot;pig&quot;, and find &quot;cat&quot; then continue</li>
  <li>Look up a key called &quot;cat&quot;, and find &quot;dog&quot; then continue</li>
  <li>Look up a key called &quot;dog&quot;, and find &quot;ant&quot; then continue</li>
  <li>Look up a key called &quot;ant&quot;, and find no associated value, and so it
  would return &quot;ant&quot;</li>
  </ol>
  <p>This is the data:</p>
  <pre><code>d = {'bat': 'pig', 'pig': 'cat', 'cat': 'dog', 'dog': 'ant', 'cow': 'bee', 'bee': 'elk', 'elk': 'fly', 'ewe': 'cod', 'cod': 'hen', 'hog': 'fox', 'fox': 'jay', 'jay': 'doe', 'rat': 'ram', 'ram': 'rat'}
  </code></pre>
  <p>This is my function below where I am trying learn recursion...and understand why my function doesn't <code>return False</code> when a key saved to <code>MEMORY</code> has a value greater than 2.</p>
  <pre><code>def rabbit_hole(dictionry,key,MEMORY={}):
      
      #print(MEMORY)
      
      if key in MEMORY:
          MEMORY[key] += 1
          
      else:
          MEMORY[key] = 1
          
  
      for val in MEMORY.values():
          #print(val)
  
          if val == 2:
              return False # &lt;--- why not working?
  
      for k,v in dictionry.items():
          if k == key:
              
              # recursive call
              rabbit_hole(dictionry,v,MEMORY)
  
      #print(&quot;return last added dict key&quot;)
      return list(MEMORY)[-1]
  </code></pre>
  <p>Any tips appreciated not a lot of wisdom here...if I run:</p>
  <pre><code>print(rabbit_hole(d, &quot;bat&quot;))
  print(rabbit_hole(d, &quot;ewe&quot;))
  print(rabbit_hole(d, &quot;jay&quot;))
  print(rabbit_hole(d, &quot;yak&quot;))
  print(rabbit_hole(d, &quot;rat&quot;))
  </code></pre>
  <p>The code above returns:</p>
  <pre><code>ant
  hen
  doe
  yak
  ram
  </code></pre>
  <p>But its supposed to return a <code>False</code> on <code>rat</code> like this:</p>
  <pre><code>ant
  hen
  doe
  yak
  False
  </code></pre>