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

Viewed 45

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)])]
2 Answers

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)
Related