Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python 딕셔너리에서 여러 키의 존재 여부를 확인하는 3가지 방법

Python으로 데이터 분석을 진행하다 보면, 특정 값들이 딕셔너리(dictionary)의 키로 존재하는지 먼저 확인해야 하는 경우가 자주 발생합니다. 이후 분석 단계에서는 실제로 존재하는 키만을 대상으로 작업해야 하기 때문입니다. 이 글에서는 여러 개의 키가 딕셔너리에 모두 포함되어 있는지 확인하는 세 가지 방법을 소개합니다.

1. 비교 연산자(Comparison Operator) 활용

확인하고자 하는 키들을 집합(set)에 담은 뒤, 딕셔너리의 키 집합과 비교하는 방법입니다. >= 연산자는 딕셔너리의 키들이 주어진 키 집합을 모두 포함하고 있는지를 검사합니다.

예제 코드

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}

# 비교 연산자 사용
if(Adict.keys()) >= check_keys:
    print("All keys are present")
else:
    print("All keys are not present")
# 새로운 키 조합으로 확인
check_keys={"Mon","Fri"}
if(Adict.keys()) >= check_keys:
    print("All keys are present")
else:
    print("All keys are not present")

실행 결과

All keys are present
All keys are not present

2. all() 함수 활용

이 방법은 반복문(for loop)과 all() 함수를 함께 사용하여 각 키의 존재 여부를 하나씩 검사합니다. all() 함수는 확인 대상 키 집합의 모든 요소가 딕셔너리에 존재할 때만 True를 반환합니다.

예제 코드

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}

# all() 함수 사용
if all(key in Adict for key in check_keys):
    print("All keys are present")
else:
    print("All keys are not present")
# 새로운 키 조합으로 확인
check_keys={"Mon","Fri"}
if all(key in Adict for key in check_keys):
    print("All keys are present")
else:
    print("All keys are not present")

실행 결과

All keys are present
All keys are not present

3. issubset() 메서드 활용

확인하려는 키들을 집합으로 만든 후, 해당 집합이 딕셔너리 키들의 부분집합(subset)인지 검증하는 방식입니다. 이를 위해 issubset() 메서드를 사용합니다.

예제 코드

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys=set(["Tue","Thu"])

# issubset() 사용
if (check_keys.issubset(Adict.keys())):
    print("All keys are present")
else:
    print("All keys are not present")
# 새로운 키 조합으로 확인
check_keys=set(["Mon","Fri"])
if (check_keys.issubset(Adict.keys())):
    print("All keys are present")
else:
    print("All keys are not present")

실행 결과

All keys are present
All keys are not present

마무리

세 가지 방법 모두 동일한 결과를 제공하지만, 상황에 따라 적합한 방식이 다릅니다. 간결한 집합 연산이 필요하다면 비교 연산자나 issubset()이 유용하고, 조건 로직을 더 세밀하게 제어하고 싶다면 all() 함수와 제너레이터 표현식을 조합하는 것이 좋습니다. 코드의 가독성과 성능 요구 사항을 고려하여 적절한 방법을 선택하시기 바랍니다.