Python list of dictionaries search
Here is a code snippet that demonstrates how to search for a specific value in a list of dictionaries in Python:
# list of dictionaries
data = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Charlie'}]
# search value
search_value = 'Bob'
# search function
def search_list_of_dicts(data, search_value):
result = []
for item in data:
if search_value in item.values():
result.append(item)
return result
# call the function and print the result
result = search_list_of_dicts(data, search_value)
print(result)
Watch a video course
Python - The Practical Guide
This code will return the dictionary containing 'Bob'
[{'id': 2, 'name': 'Bob'}]
You can use different searching method for searching the data in list of dictionaries like using filter function with lambda function, list comprehension, or generator expression.