Python 如何从带条件的词典列表中提取词典
如何使用条件从json中提取 我有一本字典的目录。我需要根据一些条件提取一些词典Python 如何从带条件的词典列表中提取词典,python,dictionary,Python,Dictionary,如何使用条件从json中提取 我有一本字典的目录。我需要根据一些条件提取一些词典 如果是交叉场,我需要“和”条件 对于相同的字段数组,我需要设置或条件 我需要搜索主题,它是物理或会计这是字段数组(或)语句 及 我需要搜索typeisPermanent或GUEST条件这是字段数组(或)语句 及 我需要搜索位置是否为NY(&)条件 预期的输出是id[{'id':2,'name':'AB','subject':['Physics','Engineering'],'type':'Perma
- 如果是交叉场,我需要“和”条件
- 对于相同的字段数组,我需要设置或条件
主题
,它是物理
或会计
这是字段数组(或)语句
及
type
isPermanent
或GUEST
条件这是字段数组(或)语句
及
位置
是否为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子句的简单方法解决了这个问题。和
条件是通过嵌套的if
完成的,而或
条件只是通过或
完成的
中的运算符用于字符串值和列表值,因此可以互换使用,并产生预期输出。但是,这种方法期望没有像XYZ会计
这样的特定主题
result=[]
对于测试中的元素:
#检查位置
如果元素['Location']='NY':
#检查科目
subject=elem['subject']
如果科目为“会计学”或“物理学”:
#支票类型
元素类型=元素['type']
如果要素类型为“永久”或要素类型为“来宾”:
#将元素添加到结果中,因为所有条件都为true
结果追加(elem)
这里的问题主要是数据不统一,有时是字符串,有时是列表。让我们试试:
# turns the values into set for easy comparison
def get_set(d,field):
return {d[field]} if isinstance(d[field], str) else set(d[field])
# we use this to filter
def validate(d):
# the three lines below corresponds to the three conditions listed
return get_set(d,'subject').intersection({'Physics','Accounting'}) and \
get_set(d,'type').intersection({'Permanent', 'Guest'}) and \
get_set(d,'Location')=={'NY'}
result = [d for d in test if validate(d)]
输出:
[{'id': 2,
'name': 'AB',
'subject': ['Physics', 'Engineering'],
'type': 'Permanent',
'Location': 'NY'},
{'id': 4,
'name': 'ABCD',
'subject': ['Physics', 'Engineering'],
'type': ['Contract', 'Guest'],
'Location': 'NY'}]
[{'id': 2,
'name': 'AB',
'subject': ['Physics', 'Engineering'],
'type': 'Permanent',
'Location': 'NY'},
{'id': 4,
'name': 'ABCD',
'subject': ['Physics', 'Engineering'],
'type': ['Contract', 'Guest'],
'Location': 'NY'}]