检查字典列表中是否已经存在值? [英] Check if value already exists within list of dictionaries?
本文介绍了检查字典列表中是否已经存在值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Python字典列表,如下所示:
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
推荐答案
这里是一种方法:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
括号中的部分是一个生成器表达式,对于具有要查找的键值对的每个词典,返回True
,否则返回False
.
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
.
如果密钥也可能丢失,则上面的代码可以为您提供KeyError
.您可以使用get
并提供默认值来解决此问题.
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 not any(d.get('main_color', None) == 'red' for d in a):
# does not exist
这篇关于检查字典列表中是否已经存在值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文