检查字典列表中是否已经存在值?

检查字典列表中是否已经存在值?

问题描述:

我有一个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