Python:如何通过叶值过滤n嵌套的命令? [英] Python: How can I filter a n-nested dict of dicts by leaf value?

查看:103
本文介绍了Python:如何通过叶值过滤n嵌套的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  d = {'食物':{'Fruit' :{'苹果':{'黄金'':['黄'],
'格兰尼史密斯':['绿色],
'富士':['红'],
$,
'Cherries':['Red'],
'香蕉':['黄'],
'葡萄':{'红葡萄' ],
'绿色葡萄':['绿色],
},
},
'甜点':{'Baked Ds':{'Cakes'黄色蛋糕':['黄色],
'红色天鹅绒':['红色],
},
'Cookies':['Yellow'],
},
},
'Steak':['Red'],
},
'Other':['Blue'],
}

所以基本上n-nested dict,其中每个值都是另一个dict或包含单个项目的列表。



我们想要通过单个列表项过滤掉,红,结果将是:

  d = {'食物':{'水果':{'苹果''{'红'',
},
'樱桃':['红'],
'葡萄':{'红葡萄' '],
},
},
'甜品':{'Baked Ds':{'Cakes':{'Red Velvet':['Red'],
},
},
},
'Steak ':['Red'],
},
}

结构保持不变,但所有没有红色作为其列表项的内容都将被删除,一直在层次结构中。



任何建议?我已经搞砸了一段时间,并提出了这一点,但似乎不起作用:

  def filterNestedDict(node,searchItem):
if isinstance(node,list):
return node
else:
为key,node.iteritems()中的值:
如果isinstance(value,dict)和值不是{}:
return {key:filterNestedDict(value,searchItem)}
elif searchItem in value:
return {key:filterNestedDict(value, searchItem)}

return filterNestedDict(bigTree,searchItem)

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



谢谢!

解决方案

你很亲密,这应该是你的窍门:

  def filter_nested_dict(node,search_term) :
if isinstance(node,list):
if node [0] == search_term:
返回节点
else:
返回无
else:
dupe_node = {}
为key,val在node.iteritems()中:
cur_node = filter_nested_dict(val,search_term)
如果cur_node:
dupe_node [key] = cur_node
返回dupe_node或无


I've got a dict that looks something like this:

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

So basically, an n-nested dict, where each value is either another dict or a list containing a single item.

Let's say that I want to filter this by a single list item, say, 'Red' such that the result would be:

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

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.

Any suggestions? I've messed around with this for a while and came up with this, but it doesn't seem to work:

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)

I suspect it's just an issue of recursion, but any suggestions would be greatly appreciated.

Thanks!

解决方案

You were pretty close, this should do the trick for you:

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

这篇关于Python:如何通过叶值过滤n嵌套的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆