Check if value already exists within list of dictionaries?
I've got a Python list of dictionaries, as follows:
a = [
{'main_color':开发者_Go百科 '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
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
Maybe this helps:
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
def in_dictlist(key, value, my_dictlist):
for entry in my_dictlist:
if entry[key] == value:
return entry
return {}
print in_dictlist('main_color','red', a)
print in_dictlist('main_color','pink', a)
Based on @Mark Byers great answer, and following @Florent question, just to indicate that it will also work with 2 conditions on list of dics with more than 2 keys:
names = []
names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})
if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):
print('Not exists!')
else:
print('Exists!')
Result:
Exists!
Perhaps a function along these lines is what you're after:
def add_unique_to_dict_list(dict_list, key, value):
for d in dict_list:
if key in d:
return d[key]
dict_list.append({ key: value })
return value
Just another way to do what the OP asked:
if not filter(lambda d: d['main_color'] == 'red', a):
print('Item does not exist')
filter
would filter down the list to the item that OP is testing for. The if
condition then asks the question, "If this item is not there" then execute this block.
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'}]
Following works out for me.
#!/usr/bin/env python
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
found_event = next(
filter(
lambda x: x['main_color'] == 'red',
a
),
#return this dict when not found
dict(
name='red',
value='{}'
)
)
if found_event:
print(found_event)
$python /tmp/x
{'main_color': 'red', 'second_color': 'blue'}
精彩评论