的Python:我如何过滤通过叶子值类型的字典正嵌套的字典?(Python: How can I f

2019-09-18 10:08发布

我有一个字典,看起来是这样的:

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'],
    }

因此,基本上,正嵌套字典,其中每个值可以是另一字典或一个包含单个条目的列表。

比方说,我想通过一个单独的列表项过滤此,说,“红”这样的结果将是:

d = {'Food': {'Fruit'  : {'Apples'    : {'Fuji'        : ['Red'],    
                                        },
                          'Cherries'  : ['Red'],
                          'Grapes'    : {'Red Grapes'  : ['Red'], 
                                        },
                          },
              'Dessert': {'Baked Ds' : {'Cakes'        : {'Red Velvet'  : ['Red'],
                                                          },
                                        },
                          },
              'Steak'  : ['Red'],
             },
    }

这样的结构保持不变,但不具有“红色”作为其列表项都被删除,一路上扬的层次结构。

有什么建议么? 我搞砸周围的这一段时间,并用此来了,但它似乎不工作:

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)

我怀疑这只是递归的问题,但任何建议,将不胜感激。

谢谢!

Answer 1:

你是非常接近,这应该为你做的伎俩:

def filter_nested_dict(node, search_term):
    if isinstance(node, list):
        if node[0] == search_term:
            return node
        else:
            return None
    else:
        dupe_node = {}
        for key, val in node.iteritems():
            cur_node = filter_nested_dict(val, search_term)
            if cur_node:
                dupe_node[key] = cur_node
        return dupe_node or None


Answer 2:

from collections import Mapping


def yield_values_2(d):
  for key in d.keys():
    if isinstance(d[key], Mapping):
      yield_values_2(d[key]) 
      if not d[key]:
        del d[key]
    elif d[key] != ["Red"]:
      del d[key]

d = {'Food': {'Fruit'  : {'Apples'    : {'Fuji'        : ['Red'], 'Fuji2': ['Blue']    
                                        },
                                                                  'Cherries'  : ['Red'],
                                                                                            'Grapes'    : {'Red Grapes'  : ['Red'], 
                                                                                                                                    },
                                                                                                                                                              },
                                                                                                                                                                            'Dessert': {'Baked Ds' : {'Cakes'        : {'Red Velvet'  : ['Red'],
                                                                                                                                                                                                                                      },
                                                                                                                                                                                                                                                                              },
                                                                                                                                                                                                                                                                                                        },
                                                                                                                                                                                                                                                                                                                      'Steak'  : ['Red'],
                                                                                                                                                                                                                                                                                                                                   },
                                                                                                                                                                                                                                                                                                                                       }

print d
yield_values_2(d)
print d


文章来源: Python: How can I filter a n-nested dict of dicts by leaf value?