Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从带条件的词典列表中提取词典_Python_Dictionary - Fatal编程技术网

Python 如何从带条件的词典列表中提取词典

Python 如何从带条件的词典列表中提取词典,python,dictionary,Python,Dictionary,如何使用条件从json中提取 我有一本字典的目录。我需要根据一些条件提取一些词典 如果是交叉场,我需要“和”条件 对于相同的字段数组,我需要设置或条件 我需要搜索主题,它是物理或会计这是字段数组(或)语句 及 我需要搜索typeisPermanent或GUEST条件这是字段数组(或)语句 及 我需要搜索位置是否为NY(&)条件 预期的输出是id[{'id':2,'name':'AB','subject':['Physics','Engineering'],'type':'Perma

如何使用条件从json中提取

我有一本字典的目录。我需要根据一些条件提取一些词典

  • 如果是交叉场,我需要“和”条件

  • 对于相同的字段数组,我需要设置或条件

  • 我需要搜索
    主题
    ,它是
    物理
    会计
    这是字段数组(或)语句

  • 我需要搜索
    type
    is
    Permanent
    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'}]