title: Python: How can I filter a n-nested dict of dicts by leaf value?
body: <p>I've got a dict that looks something like this:</p>
  
  <pre><code>d = {'Food': {'Fruit'  : {'Apples'    : {'Golden Del.'  : ['Yellow'],
                                           'Granny Smith' : ['Green'],
                                           'Fuji'         : ['Red'],    
                                          },
                            'Cherries'  : ['Red'],
                            'Bananas'   : ['Yellow'],
                            'Grapes'    : {'Red Grapes'   : ['Red'],
                                           'Green Grapes' : ['Green'],  
                                          },
                            },
                'Dessert': {'Baked Ds' : {'Cakes'         : {'Yellow Cake' : ['Yellow'],
                                                             'Red Velvet'  : ['Red'],
                                                            },
                                           'Cookies'      : ['Yellow'],
                                          },
                            },
                'Steak'  : ['Red'],
               },
       'Other': ['Blue'],
      }
  </code></pre>
  
  <p>So basically, an n-nested dict, where each value is either another dict or a list containing a single item.</p>
  
  <p>Let's say that I want to filter this by a single list item, say, 'Red' such that the result would be:</p>
  
  <pre><code>d = {'Food': {'Fruit'  : {'Apples'    : {'Fuji'        : ['Red'],    
                                          },
                            'Cherries'  : ['Red'],
                            'Grapes'    : {'Red Grapes'  : ['Red'], 
                                          },
                            },
                'Dessert': {'Baked Ds' : {'Cakes'        : {'Red Velvet'  : ['Red'],
                                                            },
                                          },
                            },
                'Steak'  : ['Red'],
               },
      }
  </code></pre>
  
  <p>So that the structure remains the same but everything that doesn't have 'Red' as its list item is removed, all the way up the hierarchy.</p>
  
  <p>Any suggestions? I've messed around with this for a while and came up with this, but it doesn't seem to work:</p>
  
  <pre><code>def filterNestedDict(node, searchItem):
      if isinstance(node,list):
          return node
      else:
          for key, value in node.iteritems():
              if isinstance(value,dict) and value is not {}:
                  return {key: filterNestedDict(value,searchItem)}
              elif searchItem in value:
                  return {key: filterNestedDict(value,searchItem)}
  
  return filterNestedDict(bigTree, searchItem)
  </code></pre>
  
  <p>I suspect it's just an issue of recursion, but any suggestions would be greatly appreciated.</p>
  
  <p>Thanks!</p>