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

问题描述 投票:0回答:8

我有一个 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
python list dictionary search key
8个回答
401
投票

这是一种方法:

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

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

True
,否则为
False
.


如果钥匙也可能丢失,上面的代码可以给你一个

KeyError
。您可以使用
get
并提供默认值来解决此问题。如果您不提供 default 值,则返回
None

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

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)

7
投票

基于@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
投票

也许沿着这些路线的功能就是您所追求的:

 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

4
投票

做OP要求的另一种方式:

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

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


1
投票

我认为检查密钥是否存在会更好一些,正如一些评论者在首选答案下所问的在这里输入链接描述

所以,我会在行尾添加一个小的 if 子句:


input_key = 'main_color'
input_value = 'red'

if not any(_dict[input_key] == input_value for _dict in a if input_key in _dict):
    print("not exist")

我不确定,如果错了,但我认为 OP 要求检查键值对是否存在,如果不存在,则应添加键值对。

在这种情况下,我会建议一个小功能:

a = [{ 'main_color': 'red', 'second_color': 'blue'},
     { 'main_color': 'yellow', 'second_color': 'green'},
     { 'main_color': 'yellow', 'second_color': 'blue'}]

b = None

c = [{'second_color': 'blue'},
     {'second_color': 'green'}]

c = [{'main_color': 'yellow', 'second_color': 'blue'},
     {},
     {'second_color': 'green'},
     {}]


def in_dictlist(_key: str, _value :str, _dict_list = None):
    if _dict_list is None:
        # Initialize a new empty list
        # Because Input is None
        # And set the key value pair
        _dict_list = [{_key: _value}]
        return _dict_list

    # Check for keys in list
    for entry in _dict_list:
        # check if key with value exists
        if _key in entry and entry[_key] == _value:
            # if the pair exits continue
            continue
        else:
            # if not exists add the pair
            entry[_key] = _value
    return _dict_list


_a = in_dictlist("main_color", "red", a )
print(f"{_a=}")
_b = in_dictlist("main_color", "red", b )
print(f"{_b=}")
_c = in_dictlist("main_color", "red", c )
print(f"{_c=}")

输出:

_a=[{'main_color': 'red', 'second_color': 'blue'}, {'main_color': 'red', 'second_color': 'green'}, {'main_color': 'red', 'second_color': 'blue'}]
_b=[{'main_color': 'red'}]
_c=[{'main_color': 'red', 'second_color': 'blue'}, {'main_color': 'red'}, {'second_color': 'green', 'main_color': 'red'}, {'main_color': 'red'}]

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'}

0
投票

有两种方法可以检查字典列表中是否存在特定键的值,如下所示:

a = [
    {'main_color': 'red', 'second_color':'blue'},
    {'main_color': 'yellow', 'second_color':'green'},
    {'main_color': 'yellow', 'second_color':'blue'}
]

# The 1st way
print(any(dict['main_color'] == 'red' for dict in a)) # True
print(any(dict['main_color'] == 'green' for dict in a)) # False

# The 2nd way
print(any('red' == dict['main_color'] for dict in a)) # True
print(any('green' == dict['main_color'] for dict in a)) # False

此外,下面这段代码可以检查一个值是否存在于字典列表中:

print(any('red' in dict.values() for dict in a)) # True
print(any('green' in dict.values() for dict in a)) # True
print(any('black' in dict.values() for dict in a)) # False
© www.soinside.com 2019 - 2024. All rights reserved.