파이썬에서 키가 사전에 있는지 확인하는 방법

Jinku Hu 2023년10월10일
파이썬에서 키가 사전에 있는지 확인하는 방법

주어진 키가 Python 사전에 있는지 확인하는 방법에 대한 질문은 튜토리얼 여기에서 더 많은 정보를 찾을 수 있는 Python 멤버십 확인 주제에 속합니다.

in 키워드는 사전 멤버십 확인을 수행하는 데 사용됩니다. 아래 코드 예를 참조하십시오

dic = {"A": 1, "B": 2}


def dicMemberCheck(key, dicObj):
    if key in dicObj:
        print("Existing key")
    else:
        print("Not existing")


dicMemberCheck("A")
dicMemberCheck("C")
Existing key
Not existing
정보

주어진 키가 사전에 있는지 확인하는 다른 솔루션을 가질 수 있습니다.

if key in dicObj.keys()

방금 보여 드린 솔루션으로 동일한 결과를 얻을 수 있습니다. 그러나이 dicObj.keys()메소드는 사전 키를 목록으로 변환하는 데 시간이 더 걸리기 때문에 약 4 배 느립니다.

아래의 실행 시간 성능 비교 테스트를 참조 할 수 있습니다.

>>> import timeit
>>> timeit.timeit('"A" in dic', setup='dic = {"A":1, "B":2}',number=1000000)
0.053480884567733256
>>> timeit.timeit('"A" in dic.keys()', setup='dic = {"A":1, "B":2}',number=1000000)
0.21542178873681905
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - Python Dictionary