python - 如果字典中存在特定键项,如何获取列表中字典的索引

标签 python

我有一个 list 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'

我试图做的是加入列表参数并检查它们是否包含标签,但它不起作用,而且也不完全是我想要做的。我只想检查标签是否包含 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]

关于python - 如果字典中存在特定键项,如何获取列表中字典的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66598176/

相关文章:

Python + SQLite : Unable to determine cause of incorrect number of bindings supplied error

python - 如果句子中的所有单词都是小写,我如何返回 "Yes"?

python - 子例程参数未从 Python 正确传递到 Fortran

python - 如何在 Python 2.7 中编写 unicode csv

python - 如何求解非负整数的线性方程组?

python - 文档中的单元测试示例引发 AttributeError

java - 马尔可夫链 : Finding terminal state calculation

python - Pandas:加速 groupby

Python - 检查今天是否创建了文件

python - 从 Streamlit 下载 python-pptx