小编use*_*107的帖子

Python:如何通过叶值过滤n-nested dicts的dict?

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

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'],
    }
Run Code Online (Sandbox Code Playgroud)

所以基本上是一个n嵌套的dict,其中每个值都是另一个dict或包含单个项的列表.

假设我想通过单个列表项过滤它,例如"Red",结果将是:

d = {'Food': {'Fruit'  : {'Apples'    : {'Fuji'        : ['Red'],    
                                        },
                          'Cherries'  : …
Run Code Online (Sandbox Code Playgroud)

python dictionary nested

7
推荐指数
1
解决办法
2114
查看次数

标签 统计

dictionary ×1

nested ×1

python ×1