values() 에서 in 연산자 사용하기
이 단계에서는 in 연산자를 사용하여 딕셔너리 값 내에 특정 값이 존재하는지 확인하는 방법을 배우게 됩니다. in 연산자는 Python 에서 데이터를 검색하고 유효성을 검사하는 강력한 도구입니다.
이전 단계에서 계속해서 동일한 딕셔너리 my_dict를 사용해 보겠습니다. 값 "Alice"가 딕셔너리의 값에 존재하는지 확인합니다.
~/project 디렉토리의 dictionary_example.py 파일을 수정하여 다음 코드를 포함합니다.
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Check if "Alice" is in the values
if "Alice" in my_dict.values():
print("Alice is in the dictionary values")
else:
print("Alice is not in the dictionary values")
dictionary_example.py에 변경 사항을 저장하고 다시 실행합니다.
python dictionary_example.py
출력은 다음과 같아야 합니다.
Alice is in the dictionary values
이제 딕셔너리에 존재하지 않는 값, 예를 들어 "Bob"을 확인해 보겠습니다.
dictionary_example.py 파일을 수정하여 "Alice" 대신 "Bob"을 확인하도록 합니다.
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Check if "Bob" is in the values
if "Bob" in my_dict.values():
print("Bob is in the dictionary values")
else:
print("Bob is not in the dictionary values")
dictionary_example.py에 변경 사항을 저장하고 다시 실행합니다.
python dictionary_example.py
이제 출력은 다음과 같아야 합니다.
Bob is not in the dictionary values
in 연산자는 대소문자를 구분합니다. "alice" (소문자) 가 딕셔너리 값에 있는지 확인해 보겠습니다.
dictionary_example.py 파일을 수정하여 "alice"를 확인하도록 합니다.
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Check if "alice" is in the values
if "alice" in my_dict.values():
print("alice is in the dictionary values")
else:
print("alice is not in the dictionary values")
dictionary_example.py에 변경 사항을 저장하고 다시 실행합니다.
python dictionary_example.py
이제 출력은 다음과 같아야 합니다.
alice is not in the dictionary values
이것은 in 연산자가 대소문자를 구분하며 정확한 값이 발견된 경우에만 True를 반환함을 보여줍니다.