python - 根据python字典中的条件抓取数据
问题描述
我有一本像下面这样的字典。
d = {'key1': {'match': '45.56', 'key12': '45.56'},
'key2': {'key21': '45.56', 'match2': '45.56'},
'key3': {'key31': '45.56', 'key32': '45.56'},
'key4': ["key4", "key5"]}
我想在“匹配”标题下获取键名(其中键的值是匹配或匹配2),在“不匹配”标题下获取不匹配的名称。
match
key1
key2
not match
key3
key4
我尝试了以下代码,但它没有返回任何内容:
d = {'key1': {'match': '45.56', 'key12': '45.56'},
'key2': {'key21': '45.56', 'match2': '45.56'},
'key3': {'key31': '45.56', 'key32': '45.56'},
'key4': ["key4", "key5"]}
print(*[k for k in d if 'match' in d[k] or 'match2' in d[k]], sep='\n') ---only prints the matched values
解决方案
您可以使用集合差异进行列表理解以获取匹配any
项和成员资格检查以及不匹配项:
d = {'key1': {'match': '45.56', 'key12': '45.56'},
'key2': {'key21': '45.56', 'match2': '45.56'},
'key3': {'key31': '45.56', 'key32': '45.56'},
'key4': ["key4", "key5"]}
to_look = {'match', 'match2'}
match = [k for k, v in d.items() if any(x in to_look for x in v)]
not_match = set(d).difference(match)
print('match')
print(*match, sep='\n')
print('\nnot match')
print(*not_match, sep='\n')
输出:
match
key1
key2
not match
key3
key4
推荐阅读
- xpath - 如何在给定起始页面中遵循基于 xpath 的规则在 Scrapy 中抓取多个链接?
- microsoft-teams - 如何在 MS Teams 中获取当前用户的可用性(可用、下班、离开...)?
- php - 如何使用 .htaccess 重写 HTTP 获取请求
- mongodb - 运行 MongoDB 查询时,如何扩展在 robo3t 中查看的文档数量?
- php - 如何在元标记 html 中添加 img src(带有 php 脚本)
- c++ - auto const & map 迭代器的类型是什么?C++
- mysql - 如何在 Squalize 的 INSERT 函数中使用 mysql SELECT 查询
- node.js - Multer 无法在 console.log 中获取单独的字段名称
- angular-material - 如何删除 mat-select 组件的下划线
- jquery - jQuery Datatable 渲染功能不适用于多列