簡體   English   中英

如果特定鍵項在字典中,如何獲取列表中字典的索引

[英]How to get the index of a dictionary inside list if a specific key item is in the dictionary

我有一個列表intents_list這個列表包含 3 個字典,每個字典都有一個標簽(一個鍵),例如intents_list[0]有標簽hello 我想檢查哪個索引具有特定標簽。

intents_list = [{'tag': 'hello', 'patterns': ['Hello', 'Hello there'], 'responses': ['hi!', 'wassup!']}, {'tag': 'goodnight', 'patterns': ['goodnight my friend', 'wish you a good night'], 'responses': ['you two!', 'goodnight!']}]

tagstring = 'goodnight'

我試圖做的是加入列表 arguments 並檢查它們是否包含標簽,它不起作用,這不是我想要做的。 我只想檢查標簽是否包含標簽tagstring

index = [intents_list.index(index) for index in intents_list if tagstring in ''.join(intents_list[intents_list.index(index)])]

使用列表推導獲取索引:

indices = [i for i, d in enumerate(intents_list) if d['tag'] == tagstring]

像這樣的東西會起作用:

index = next(iter([i for i, x in enumerate(intents_list) if x[‘tag’] == 
tagString]), None)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM