首页 > 解决方案 > 创建一个通过询问某些值来过滤嵌套字典的函数

问题描述

我是python的初学者,试图通过询问字典中的多个值来创建一个过滤我的嵌套字典的函数,例如

filtered_options = {'a': 5, 'b': "Cloth'}

对于我的字典

my_dict = {1.0:{'a': 1, 'b': "Food', 'c': 500, 'd': 'Yams'},
           2.0:{'a': 5, 'v': "Cloth', 'c': 210, 'd': 'Linen'}}

如果我在带有这些选项的过滤器函数中输入我的字典,我应该得到一些看起来像

filtered_dict(my_dict, filtered_options = {'a': 5, 'b': "Cloth'}) 

它在我的字典中输出具有相同过滤选项的第二个键和其他键。

标签: pythonfunctiondictionary

解决方案


这应该做你想要的。

def dict_matches(d, filters):
    return all(k in d and d[k] == v for k, v in filters.items())

def filter_dict(d, filters=None):
    filters = filters or {}
    return {k: v for k, v in d.items() if dict_matches(v, filters)}

这是您测试它时会发生的情况:

>>> filters = {'a': 5, 'b': 'Cloth'}
>>> my_dict = {
...     1.0: {'a': 1, 'b': 'Food', 'c': 500, 'd': 'Yams'},
...     2.0: {'a': 5, 'b': 'Cloth', 'c': 210, 'd': 'Linen'}
... }
>>> filter_dict(my_dict, filters)
{2.0: {'b': 'Cloth', 'a': 5, 'd': 'Linen', 'c': 210}}

推荐阅读