python - 创建一个通过询问某些值来过滤嵌套字典的函数
问题描述
我是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'})
它在我的字典中输出具有相同过滤选项的第二个键和其他键。
解决方案
这应该做你想要的。
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}}
推荐阅读
- python - Python:根据另一列值从 DataFrame 中删除重复项
- android - 使用post表单数据上传axios图片总是返回网络错误
- python - 使用 SFTP 将文件从 AWS S3 传输到 Unix 服务器
- vue.js - 如何在鼠标悬停在使用 Vuetify 数据表的表格时显示按钮
- gnome - 如何将 Dconf 包添加到 buildroot
- kotlin - 如果 List 包含重复项,则对值应用更改 Kotlin
- gradle - com.sun:tools:jar 的“dependencies.dependency.systemPath”必须指定一个绝对值
- angular - 离子事件替换为 Angular Observables
- amazon-web-services - AWS 可用区标签是否跨时间/用户相同?
- c# - Microsoft.Azure.StorageException:指定的资源名称包含无效字符