简体   繁体   English

如何从有条件的字典列表中提取字典

[英]How to extract the dictionary from list of dictionary with condition

How to extract from the json with condition如何从带有条件的json中提取

I have a list of dictionary.我有一个字典列表。 I need extract some of the dictionary with some conditions我需要在某些条件下提取一些字典

  • If for cross field I need "AND" condition如果对于交叉领域,我需要“AND”条件

  • for same field array I need to OR condition对于相同的字段数组,我需要 OR 条件

  1. I need to search subject which is Physics or Accounting this is array of fields(OR) statement我需要搜索PhysicsAccounting subject ,这是字段数组(OR)语句

    AND

  2. I need to search type is Permanent or GUEST condition this is array of fields(OR) statement我需要搜索typePermanentGUEST条件,这是字段数组(OR)语句

    AND

  3. I need to search Location is NY (&) condition我需要搜索Location is 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'}]

Expected out is id [{ 'id':2,'name': 'AB','subject': ['Physics','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'}]

The following simple approach with a nested if clause solves the issue.以下带有嵌套 if 子句的简单方法解决了这个问题。 The and condition is done via the nested if and the or conditions is simply done via or . and条件是通过嵌套的if完成的,而or条件只是通过or完成。

The in operator works for string values and list values, therefore it can be used interchangeably and results in the expected out. in运算符适用于字符串值和列表值,因此它可以互换使用并产生预期的输出。 BUT this approach expects that there are no specific subjects like XYZ Accounting .但是这种方法期望没有像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)

The problem here is mostly that your data is not uniform, sometimes it's strings, sometimes it's list.这里的问题主要是你的数据不统一,有时是字符串,有时是列表。 Let's try:咱们试试吧:

# 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)]

Output:输出:

[{'id': 2,
  'name': 'AB',
  'subject': ['Physics', 'Engineering'],
  'type': 'Permanent',
  'Location': 'NY'},
 {'id': 4,
  'name': 'ABCD',
  'subject': ['Physics', 'Engineering'],
  'type': ['Contract', 'Guest'],
  'Location': 'NY'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM