如何循环浏览字典列表并对列表中的每个项应用另一个for循环?

2024-09-28 11:39:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下必须采用此格式的词典列表:

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

函数的作用是:搜索匹配的单词

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,))]})]

Tags: inbrowserid列表for条目links词典

热门问题