[英]Check if value already exists within list of dictionaries and if it does update the counter
[英]Check if value already exists within list of dictionaries?
我有一个 Python 字典列表,如下所示:
a = [
{'main_color': 'red', 'second_color':'blue'},
{'main_color': 'yellow', 'second_color':'green'},
{'main_color': 'yellow', 'second_color':'blue'},
]
我想检查列表中是否已经存在具有特定键/值的字典,如下所示:
// is a dict with 'main_color'='red' in the list already?
// if not: add item
这是一种方法:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
括号中的部分是一个生成器表达式,它为每个具有您要查找的键值对的字典返回True
,否则返回False
。
如果密钥也可能丢失,上面的代码会给你一个KeyError
。 您可以通过使用get
并提供默认值来解决此问题。 如果您不提供默认值,则返回None
。
if not any(d.get('main_color', default_value) == 'red' for d in a):
# does not exist
也许这有帮助:
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)
也许沿着这些路线的功能是您所追求的:
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
基于@Mark Byers 很好的答案,并遵循@Florent 问题,只是为了表明它也适用于具有 2 个以上键的 dic 列表中的 2 个条件:
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!')
结果:
Exists!
做OP要求的另一种方式:
if not filter(lambda d: d['main_color'] == 'red', a):
print('Item does not exist')
filter
会将列表过滤到 OP 正在测试的项目。 if
条件然后询问问题,“如果这个项目不存在”然后执行这个块。
以下对我有用。
#!/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'}
我认为检查密钥是否存在会更好一些,因为一些评论者在首选答案下询问,请在此处输入链接描述
所以,我会在行尾添加一个小的 if 子句:
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")
我不确定,如果错了,但我认为 OP 要求检查键值对是否存在,如果不存在,则应添加键值对。
在这种情况下,我会建议一个小功能:
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=}")
输出:
_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'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.