Search A List Of Dictionary In Python
Solution 1:
Use next()
:
d = next((d for d in Mylist if d['Stringa'] == 'ABC'), None)
if d isnotNone: # foundprint(d)
See Python: find first element in a sequence that matches a predicate.
Solution 2:
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.
Solution 3:
Here is another option, which allows you a bit more flexibility:
defsearch_things(haystack, needle, value):
for i in haystack:
if i.get(needle) == value:
return i
returnNone# Not needed, None is returned by default# you can use this to return some other default value
found = search_things(MyList, 'StringA', 'ABC')
if found:
print('Found it! {}'.format(found))
else:
print('Not found')
Post a Comment for "Search A List Of Dictionary In Python"