I think a check if the key exists would be a bit better, as some commenters asked under the preferred answer enter link description here
So, I would add a small if clause at the end of the line:
input_key = 'main_color'
input_value = 'red'
if not any(_dict[input_key] == input_value for _dict in a if input_key in _dict):
print("not exist")
I'm not sure, if wrong but I think the OP asked to check, if the key-value pair exists and if not the key value pair should be added.
In this case, I would suggest a small function:
a = [{ 'main_color': 'red', 'second_color': 'blue'},
{ 'main_color': 'yellow', 'second_color': 'green'},
{ 'main_color': 'yellow', 'second_color': 'blue'}]
b = None
c = [{'second_color': 'blue'},
{'second_color': 'green'}]
c = [{'main_color': 'yellow', 'second_color': 'blue'},
{},
{'second_color': 'green'},
{}]
def in_dictlist(_key: str, _value :str, _dict_list = None):
if _dict_list is None:
# Initialize a new empty list
# Because Input is None
# And set the key value pair
_dict_list = [{_key: _value}]
return _dict_list
# Check for keys in list
for entry in _dict_list:
# check if key with value exists
if _key in entry and entry[_key] == _value:
# if the pair exits continue
continue
else:
# if not exists add the pair
entry[_key] = _value
return _dict_list
_a = in_dictlist("main_color", "red", a )
print(f"{_a=}")
_b = in_dictlist("main_color", "red", b )
print(f"{_b=}")
_c = in_dictlist("main_color", "red", c )
print(f"{_c=}")
Output:
_a=[{'main_color': 'red', 'second_color': 'blue'}, {'main_color': 'red', 'second_color': 'green'}, {'main_color': 'red', 'second_color': 'blue'}]
_b=[{'main_color': 'red'}]
_c=[{'main_color': 'red', 'second_color': 'blue'}, {'main_color': 'red'}, {'second_color': 'green', 'main_color': 'red'}, {'main_color': 'red'}]