Python 检查字典列表中是否已经存在值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3897499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if value already exists within list of dictionaries?
提问by AP257
I've got a Python list of dictionaries, as follows:
我有一个 Python 字典列表,如下所示:
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
采纳答案by Mark Byers
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 Truefor each dictionary that has the key-value pair you are looking for, otherwise False.
括号中的部分是一个生成器表达式,它True为每个具有您要查找的键值对的字典返回,否则返回False.
If the key could also be missing the above code can give you a KeyError. You can fix this by using getand providing a default value.
如果密钥也可能丢失,上面的代码可以给你一个KeyError. 您可以通过使用get并提供默认值来解决此问题。
if not any(d.get('main_color', None) == 'red' for d in a):
# does not exist
回答by Cameron
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
回答by Tony Veijalainen
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 this in my_dictlist:
if this[key] == value:
return this
return {}
print in_dictlist(('main_color','red'), a)
print in_dictlist(('main_color','pink'), a)
回答by Amitsas1
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:
基于@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!')
Result:
结果:
Exists!

