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

时间:2010-10-09 19:12:03

标签: python list dictionary

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

6 个答案:

答案 0 :(得分:199)

这是一种方法:

if not any(d['main_color'] == 'red' for d in a):
    # does not exist

括号中的部分是一个生成器表达式,它为每个具有您要查找的键值对的字典返回True,否则为False


如果密钥也可能丢失,上面的代码可以为您提供KeyError。您可以使用get并提供默认值来解决此问题。

if not any(d.get('main_color', None) == 'red' for d in a):
    # does not exist

答案 1 :(得分:5)

也许这会有所帮助:

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)

答案 2 :(得分:3)

沿着这些方向的功能也许就是你所追求的:

 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

答案 3 :(得分:1)

基于@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!

答案 4 :(得分:1)

只是按照 OP 要求执行的另一种方式:

 if not filter(lambda d: d['main_color'] == 'red', a):
     print('Item does not exist')

filter 会将列表过滤到 OP 正在测试的项目。然后 if 条件提出问题,“如果此项目不存在”,则执行此块。

答案 5 :(得分:0)

以下对我有用。

    #!/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'}
相关问题