Appearance
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:
Search for a specific value in a list of dictionaries in Python
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)
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
This code will return the dictionary containing 'Bob'
return the dictionary containing 'Bob' name
console
[{'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.