I have a list of dictionaries and I want to find if a value exits in the list and if it exists return the dictionary.
For example
Mylist= [{'Stringa': "ABC",
'Stringb': "DE",
'val': 5},
{'Stringa': "DEF",
'Stringb': "GHI",
'val': 6}]
I want to find if for any dictionary
dict["stringa"]=="ABC". If yes return the corresponding dictionary.
I used the function "any"
any(d['Stringa'] == 'ABC' for d in Mylist)
but it just gives True/False. How can I get the corresponding dictionary.
解决方案
any will just check if any of the items in the iterable satisfy the condition or not. It cannot be used to retrieve matching items.
Use a list comprehension to get the list of matched items, like this
matches = [d for d in Mylist if d['Stringa'] == 'ABC']
This will iterate through the list of dictionaries and whenever it finds a match, it will include that in the result list. And then you can access the actual dictionary with its index in the list, like matches[0].
Alternatively, you can use a generator expression, like this
matches = (d for d in Mylist if d['Stringa'] == 'ABC')
and you can get the next matched item from the list, with
actual_dict = next(matches)
This will give you the actual dictionary. If you want to get the next matched item, you can call next with the generator expression again. If you want to get all the matching items at once, as a list, you can simply do
list_of_matches = list(matches)
Note: Calling next() will raise an exception, if there are no more items to be retrieved from the generator. So, you can pass a default value to be returned.
actual_dict = next(matches, None)
Now, actual_dict will be None if the generator is exhausted.