소개
이 랩에서는 Python 딕셔너리가 특정 개수의 키를 가지고 있는지 확인하는 방법을 배우게 됩니다. 이는 내장 함수 len()을 사용하여 딕셔너리 크기를 탐색하여 키 - 값 쌍의 개수를 결정하는 것을 포함합니다.
Python 스크립트를 생성하여 딕셔너리를 정의하고, len()을 사용하여 크기를 얻고, 결과를 출력합니다. 또한 빈 딕셔너리를 사용하여 출력을 관찰하는 실험도 진행합니다. 이 실습을 통해 len()을 효과적으로 사용하여 딕셔너리의 키 개수를 확인하는 방법을 보여줍니다.
딕셔너리 크기 탐색
이 단계에서는 Python 에서 딕셔너리의 크기를 결정하는 방법을 배우게 됩니다. 딕셔너리의 크기는 딕셔너리가 포함하고 있는 키 - 값 쌍의 개수를 의미합니다. 딕셔너리의 크기를 아는 것은 딕셔너리가 비어 있는지 확인하거나 특정 용량에 도달했는지 결정하는 등 다양한 작업에 유용할 수 있습니다.
딕셔너리의 크기를 찾기 위해 내장 함수 len()을 사용할 수 있습니다. 이 함수는 딕셔너리에 있는 항목 (키 - 값 쌍) 의 개수를 반환합니다.
이를 탐색하기 위해 간단한 Python 스크립트를 만들어 보겠습니다.
LabEx 환경에서 VS Code 편집기를 엽니다.
~/project디렉토리에dictionary_size.py라는 새 파일을 생성합니다.touch ~/project/dictionary_size.py편집기에서
dictionary_size.py파일을 열고 다음 Python 코드를 추가합니다.## Create a sample dictionary my_dict = { "name": "Alice", "age": 30, "city": "New York" } ## Get the size of the dictionary using the len() function dict_size = len(my_dict) ## Print the size of the dictionary print("The size of the dictionary is:", dict_size)이 코드는 먼저 세 개의 키 - 값 쌍을 가진
my_dict라는 딕셔너리를 생성합니다. 그런 다음len()함수를 사용하여 딕셔너리의 크기를 얻어dict_size변수에 저장합니다. 마지막으로 딕셔너리의 크기를 콘솔에 출력합니다.이제 터미널에서 다음 명령을 사용하여 Python 스크립트를 실행합니다.
python ~/project/dictionary_size.py다음 출력을 볼 수 있습니다.
The size of the dictionary is: 3이 출력은
len()함수가 딕셔너리의 키 - 값 쌍의 개수를 올바르게 반환함을 확인합니다.빈 딕셔너리로 시도해 보겠습니다.
dictionary_size.py파일을 다음과 같이 수정합니다.## Create an empty dictionary my_dict = {} ## Get the size of the dictionary using the len() function dict_size = len(my_dict) ## Print the size of the dictionary print("The size of the dictionary is:", dict_size)스크립트를 다시 실행합니다.
python ~/project/dictionary_size.py다음 출력을 볼 수 있습니다.
The size of the dictionary is: 0이는 빈 딕셔너리의 크기가 0 임을 보여줍니다.
키에 len() 함수 사용
이전 단계에서는 len() 함수를 사용하여 딕셔너리의 전체 키 - 값 쌍의 개수를 결정하는 방법을 배웠습니다. 이 단계에서는 .keys() 메서드와 함께 len()을 사용하여 딕셔너리의 키 개수를 찾는 방법을 탐구합니다.
.keys() 메서드는 딕셔너리의 모든 키 목록을 표시하는 뷰 객체 (view object) 를 반환합니다. 그런 다음 이 뷰 객체에 len() 함수를 사용하여 키의 개수를 얻을 수 있습니다. 이는 키 - 값 쌍의 총 개수가 아닌 키의 개수만 알아야 할 때 유용할 수 있습니다.
이를 시연하기 위해 이전 단계의 Python 스크립트를 수정해 보겠습니다.
VS Code 편집기에서
dictionary_size.py파일을 엽니다 (아직 열려 있지 않은 경우).dictionary_size.py파일을 다음 Python 코드로 수정합니다.## Create a sample dictionary my_dict = { "name": "Alice", "age": 30, "city": "New York" } ## Get the keys of the dictionary using the .keys() method keys = my_dict.keys() ## Get the number of keys using the len() function num_keys = len(keys) ## Print the number of keys print("The number of keys in the dictionary is:", num_keys)이 코드에서는 먼저
my_dict라는 딕셔너리를 생성합니다. 그런 다음.keys()메서드를 사용하여 딕셔너리의 모든 키를 포함하는 뷰 객체를 가져옵니다. 이 뷰 객체를keys변수에 저장합니다. 마지막으로len()함수를 사용하여keys뷰 객체의 키 개수를 얻고 결과를 출력합니다.터미널에서 다음 명령을 사용하여 Python 스크립트를 실행합니다.
python ~/project/dictionary_size.py다음 출력을 볼 수 있습니다.
The number of keys in the dictionary is: 3이 출력은
.keys()메서드와 함께 사용될 때len()함수가 딕셔너리의 키 개수를 올바르게 반환함을 확인합니다.이제 딕셔너리에 새로운 키 - 값 쌍을 추가하고 키 개수에 어떤 영향을 미치는지 살펴보겠습니다.
dictionary_size.py파일을 다음과 같이 수정합니다.## Create a sample dictionary my_dict = { "name": "Alice", "age": 30, "city": "New York" } ## Add a new key-value pair my_dict["occupation"] = "Engineer" ## Get the keys of the dictionary using the .keys() method keys = my_dict.keys() ## Get the number of keys using the len() function num_keys = len(keys) ## Print the number of keys print("The number of keys in the dictionary is:", num_keys)스크립트를 다시 실행합니다.
python ~/project/dictionary_size.py다음 출력을 볼 수 있습니다.
The number of keys in the dictionary is: 4이는 새로운 키 - 값 쌍을 추가하면 딕셔너리의 키 개수가 증가함을 보여줍니다.
원하는 개수와 비교
이전 단계에서는 딕셔너리의 크기를 결정하고 키의 개수를 세는 방법을 배웠습니다. 이 단계에서는 딕셔너리의 크기 (또는 키의 개수) 를 원하는 개수와 비교하는 방법을 배우게 됩니다. 이는 딕셔너리가 추가 작업을 진행하기 전에 특정 수의 키 - 값 쌍 또는 키를 가지고 있는지 확인해야 할 때 유용합니다.
이를 시연하기 위해 이전 단계의 Python 스크립트를 수정해 보겠습니다.
VS Code 편집기에서
dictionary_size.py파일을 엽니다 (아직 열려 있지 않은 경우).dictionary_size.py파일을 다음 Python 코드로 수정합니다.## Create a sample dictionary my_dict = { "name": "Alice", "age": 30, "city": "New York" } ## Desired count desired_count = 3 ## Get the size of the dictionary dict_size = len(my_dict) ## Compare with desired count if dict_size == desired_count: print("The dictionary size matches the desired count.") else: print("The dictionary size does not match the desired count.") ## Get the number of keys num_keys = len(my_dict.keys()) ## Compare the number of keys with desired count if num_keys == desired_count: print("The number of keys matches the desired count.") else: print("The number of keys does not match the desired count.")이 코드에서는 먼저
my_dict라는 딕셔너리를 생성하고desired_count변수를 3 으로 설정합니다. 그런 다음len()함수를 사용하여 딕셔너리의 크기를 구하고 이를desired_count와 비교합니다. 딕셔너리 크기가 원하는 개수와 일치하는지 여부를 나타내는 메시지를 출력합니다. 그런 다음 딕셔너리의 키 개수에 대해 동일한 프로세스를 반복합니다.터미널에서 다음 명령을 사용하여 Python 스크립트를 실행합니다.
python ~/project/dictionary_size.py다음 출력을 볼 수 있습니다.
The dictionary size matches the desired count. The number of keys matches the desired count.이 출력은 딕셔너리 크기와 키의 개수가 모두 원하는 개수인 3 과 일치함을 확인합니다.
이제 딕셔너리와 원하는 개수를 수정하여 비교가 어떻게 변경되는지 살펴보겠습니다.
dictionary_size.py파일을 다음과 같이 수정합니다.## Create a sample dictionary my_dict = { "name": "Alice", "age": 30, "city": "New York" } ## Add a new key-value pair my_dict["occupation"] = "Engineer" ## Desired count desired_count = 4 ## Get the size of the dictionary dict_size = len(my_dict) ## Compare with desired count if dict_size == desired_count: print("The dictionary size matches the desired count.") else: print("The dictionary size does not match the desired count.") ## Get the number of keys num_keys = len(my_dict.keys()) ## Compare the number of keys with desired count if num_keys == desired_count: print("The number of keys matches the desired count.") else: print("The number of keys does not match the desired count.")스크립트를 다시 실행합니다.
python ~/project/dictionary_size.py다음 출력을 볼 수 있습니다.
The dictionary size matches the desired count. The number of keys matches the desired count.이제 딕셔너리 크기와 키의 개수가 모두 업데이트된 원하는 개수인 4 와 일치합니다.
요약
이 랩에서는 len() 함수를 사용하여 Python 딕셔너리의 크기를 결정하는 방법을 배웠습니다. 이 랩에서는 이 기능을 탐구하기 위해 dictionary_size.py라는 Python 스크립트를 생성했습니다. 키 - 값 쌍으로 샘플 딕셔너리를 생성한 다음 len(my_dict)를 사용하여 딕셔너리의 항목 수를 얻고 결과를 콘솔에 출력했습니다.
또한 이 랩에서는 len() 함수가 빈 딕셔너리에서 어떻게 작동하는지 보여주었으며, 딕셔너리가 비어 있는 경우에도 키 - 값 쌍의 수를 정확하게 반환하는 기능을 강조했습니다. 이 지식은 딕셔너리가 비어 있는지 확인하거나 특정 용량에 도달했는지 확인하는 것과 같은 작업에 매우 중요합니다.



