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

202 投票
8 回答
228206 浏览
提问于 2025-04-16 05:15

我有一个包含字典的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

8 个回答

8

根据@Mark Byers的精彩回答,以及@Florent的问题,想说明的是,这个方法也适用于有两个条件的字典列表,并且这些字典里有超过两个键:

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!
8

也许这能帮到你:

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)
418

这里有一种方法可以做到:

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

撰写回答