I've got a Python list of dictionaries as follows:
a = [
{'main_color': 'red', 'second_color':'blue'},
{'main_color': 'yellow', 'second_color':'green'},
{'main_color': 'yellow', 'second_color':'blue'},
]
I'd like to check whether a dictionary with a particular key/value already exists in the list as follows:
// is a dict with 'main_color'='red' in the list already?
// if not: add item
ベストアンサー1
Here's one way to do it:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
The part in parentheses is a generator expression that returns True
for each dictionary that has the key-value pair you are looking for, otherwise False
.
If the key could also be missing the above code can give you a KeyError
. You can fix this by using get
and providing a default value. If you don't provide a default value, None
is returned.
if not any(d.get('main_color', default_value) == 'red' for d in a):
# does not exist