简体   繁体   中英

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

I have a list intents_list this list contains 3 dictionaries, each dictionary has a tag (a key), for example intents_list[0] has the tag hello . I want to check what index has a specific tag.

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'

What I tried to do was to join the list arguments and check if they contain the tag, it didn't work and it's not exactly what I want to do. I want to only check if tag contains tagstring

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

Use a list comprehension to get the indices:

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

Something like this will work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM