programing

파이썬의 사전 목록에 값이 이미 있는지 확인하시겠습니까?

javamemo 2023. 6. 19. 21:04
반응형

파이썬의 사전 목록에 값이 이미 있는지 확인하시겠습니까?

저는 다음과 같은 파이썬 사전 목록을 가지고 있습니다.

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)

@Mark Byers의 훌륭한 답변을 바탕으로 @Florent 질문에 이어 두 개 이상의 키를 가진 dic 목록의 두 가지 조건에서도 작동한다는 것을 나타냅니다.

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!

다음과 같은 기능이 필요할 수 있습니다.

 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

OP가 요청한 것을 수행하기 위한 또 다른 방법:

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

filterOP가 테스트하는 항목으로 목록을 필터링합니다.if그런 다음 조건은 "이 항목이 없는 경우"라는 질문을 하고 이 블록을 실행합니다.

선호하는 답변 아래에 질문을 받은 일부 댓글 작성자가 여기에 링크 설명을 입력하기 때문에 키가 있는지 확인하는 것이 조금 더 나을 것 같습니다.

따라서 줄 끝에 작은 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'}]

다음은 저에게 맞는 운동입니다.

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

아래와 같이 사전 목록에 특정 키의 값이 있는지 확인하는 두 가지 방법이 있습니다.

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

언급URL : https://stackoverflow.com/questions/3897499/check-if-value-already-exists-within-list-of-dictionaries-in-python

반응형