find an object in a list of dicts by an attribute in python
- User
find an object in a list of dicts by an attribute in python
- Assistant
To find an object in a list of dictionaries by a specific attribute in Python, you can use a list comprehension or a loop to iterate through each dictionary and check for the attribute value.
Here's an example using a list comprehension:
pythondef find_object_by_attribute(objects, attribute, value): return [obj for obj in objects if obj.get(attribute) == value] # Example usage objects = [ {"name": "Apple", "color": "Red"}, {"name": "Banana", "color": "Yellow"}, {"name": "Orange", "color": "Orange"} ] found_objects = find_object_by_attribute(objects, "color", "Yellow") print(found_objects)Output:
code[{"name": "Banana", "color": "Yellow"}] - User
return true if there's an object in a list of dicts with specified value in attrubute in python
- Assistant
To return
Trueif there is an object in a list of dictionaries with a specified value in an attribute in Python, you can loop through the list and check if any dictionary has the attribute matching the desired value.Here's an example that demonstrates this:
pythondef is_object_present(objects, attribute, value): for obj in objects: if obj.get(attribute) == value: return True return False # Example usage objects = [ {"name": "Apple", "color": "Red"}, {"name": "Banana", "color": "Yellow"}, {"name": "Orange", "color": "Orange"} ] print(is_object_present(objects, "color", "Yellow")) # Output: True print(is_object_present(objects, "color", "Green")) # Output: False