簡體   English   中英

檢查字典列表中是否已經存在值?

[英]Check if value already exists within list of dictionaries?

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

這是一種方法:

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

也許這有幫助:

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)

也許沿着這些路線的功能是您所追求的:

 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

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

做OP要求的另一種方式:

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

filter會將列表過濾到 OP 正在測試的項目。 if條件然后詢問問題,“如果這個項目不存在”然后執行這個塊。

以下對我有用。

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

我認為檢查密鑰是否存在會更好一些,因為一些評論者在首選答案下詢問,請在此處輸入鏈接描述

所以,我會在行尾添加一個小的 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'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM