我将如何遍历字典列表,并将另一个for循环应用于列表中的每个项目?

时间:2019-01-16 20:51:35

标签: python list loops dictionary nlp

我有下面的词典列表,必须采用这种格式:

incident keywords = [{'INC000007581874': 'ccd browser'},
                     {'INC000007581947': 'CATIA'},
                     {'INC000007582037': 'Catia'}]

我需要对列表中的每个词典条目应用搜索功能。

我一直在想for循环是可行的方法,但是我不知道如何实现它。我还认为删除'query ='ccd browser'使其适用于字典中的所有值可能是一种方法,但我不确定如何做到。

因此,在每个循环中,它将使用“ ccd浏览器”,然后接下来将使用“ CATIA”,依此类推,对于列表中的所有字典,无论列表多长。

def look_up(id,keywords):

    # Ignores case
    keywords = keywords.lower()
    for item in incident_keywords:
        # if any value contains s
        if any([keywords in v.lower() for v in item.values()]):
            # spit out the item — this is a generator function
            yield item

look_up()函数搜索单词匹配项。

def search():

    query = 'ccd browser'

    print(' ')

    choices = []
    id = []

    # iterate over at most 50 first results (can be changed)
    for result in itertools.islice(look_up(id,query), 50):
        id.append(list(result.keys()))
        choices.append(list(result.values()))

    output = process.extract(query,choices,limit=20)

    # Tuple comprehension to remove strings from tuple pairings
    removed = [tuple(j for j in i if isinstance(j, int)) for i in output]

    print('')

    zipped = [{"Links:" : [list(zip(id, removed))]}]

    pprint.pprint(list(zip(incident_keywords_2, zipped)))

Search()函数执行搜索,但不会将其应用于字典列表中的每个条目。

目前,我能够对词典列表中的第一个条目执行此操作,以提供输出:

[({'INC000007581874': 'ccd browser'}},
  {'Links:': [[(['INC000007581874'], (100,))]]})]

但是当将其应用于词典列表中的所有条目时,我需要帮助将此过程应用于词典列表中的每个条目,以提供类似于以下的输出:

[({'INC000007581874': 'ccd browser'}},
  {'Links:': [[(['INC000007581874'], (100,))]]})]

[({'INC000007581947': 'CATIA'}},
  {'Links:': [[(['INC000007581947': 'CATIA'], (100,))]], 
              [(['INC000007582037': 'Catia'], (100,))]})]

[({'INC000007582037': 'Catia'}},
  {'Links:': [[(['INC000007582037': 'Catia'], (100,))]], 
              [(['INC000007581947': 'CATIA'], (100,))]})]

0 个答案:

没有答案