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

1cosmwyk  于 2023-05-16  发布在  Python
关注(0)|答案(8)|浏览(154)

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

klsxnrf11#

这里有一个方法:

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
col17t5w

col17t5w2#

也许这会有所帮助:

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

jexiocij3#

基于@Mark Byers的伟大答案,以及以下@Florent问题,只是为了表明它也将在具有2个以上键的dics列表上的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!
jv4diomz

jv4diomz4#

也许沿着这些路线的函数就是你所追求的:

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
aamkag61

aamkag615#

只是另一种方式来做什么行动要求:

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

filter将向下过滤列表,直到OP正在测试的项目。然后if条件询问问题“如果这个项目不在那里”,然后执行这个块。

ilmyapht

ilmyapht6#

我认为检查密钥是否存在会更好一些,因为一些评论者在首选答案enter link description here下询问
所以,我会在该行末尾添加一个小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'}]
mm5n2pyu

mm5n2pyu7#

我想我能做到。

#!/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'}
uoifb46i

uoifb46i8#

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

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

相关问题