python - 如何从有条件的字典列表中提取字典
问题描述
如何从带有条件的json中提取
我有一个字典列表。我需要在某些条件下提取一些字典
如果对于跨领域我需要“AND”条件
对于相同的字段数组,我需要 OR 条件
我需要搜索
subject
这是Physics
或Accounting
这是字段数组(OR)语句和
我需要搜索
type
是Permanent
或GUEST
条件这是字段数组(OR)语句和
我需要搜索
Location
的是NY
(&) 条件
test = [{'id':1,'name': 'A','subject': ['Maths','Accounting'],'type':'Contract', 'Location':'NY'},
{ 'id':2,'name': 'AB','subject': ['Physics','Engineering'],'type':'Permanent','Location':'NY'},
{'id':3,'name': 'ABC','subject': ['Maths','Engineering'],'type':'Permanent','Location':'NY'},
{'id':4,'name':'ABCD','subject': ['Physics','Engineering'],'type':['Contract','Guest'],'Location':'NY'}]
预期出来的是 id[{ 'id':2,'name': 'AB','subject': ['Physics','Engineering'],'type':'Permanent','Location':'NY'},{'id':4,'name':'ABCD','subject': ['Physics','Engineering'],'type':['Contract','Guest'],'Location':'NY'}]
解决方案
以下带有嵌套 if 子句的简单方法解决了该问题。and
条件是通过嵌套完成的,if
而or
条件只是通过or
.
该in
运算符适用于字符串值和列表值,因此它可以互换使用并产生预期的结果。但是这种方法期望没有特定的主题,例如XYZ Accounting
.
result = []
for elem in test:
# Check Location
if elem['Location'] == 'NY':
# Check subject
subject = elem['subject']
if ('Accounting' in subject) or ('Physics' in subject):
# Check type
elem_type = elem['type']
if ('Permanent' in elem_type) or ('Guest' in elem_type):
# Add element to result, because all conditions are true
result.append(elem)
推荐阅读
- mendix - 在 Mendix 中更新实体时,数据视图未更新
- c - 给定代码场景的时间复杂度
- python - python '环境已经崩溃'
- python - 使用谷歌存储和谷歌视觉 API
- javascript - 在多级下拉菜单中,如何防止子菜单重叠
- python - 如何使用证书和 rsa 密钥连接到服务器
- tomcat - 登录到 jaspersoft 时重定向循环
- javascript - jQuery - 如何用标签包装输入标签
- amazon-cloudformation - 如何将角色传递给 cli 命令“aws cloudformation deploy”或“sam deploy”?
- ldap - 带有 Liferay 的 LDAP - 存在的未知主机