Python 딕셔너리 관리하기

PythonBeginner
지금 연습하기

소개

본 실습에서는 데이터를 키 - 값 쌍 (key-value pairs) 으로 저장하는 필수적인 데이터 구조인 Python 딕셔너리 (dictionary) 에 대한 실습 경험을 쌓게 됩니다. 딕셔너리를 생성하고 검사하는 방법, 요소에 접근하고 수정하는 방법, 항목을 추가하고 제거하는 방법, 그리고 딕셔너리 뷰 객체 (dictionary view objects) 를 다루는 방법을 배우게 됩니다. 실습이 끝날 때쯤이면 일반적인 딕셔너리 연산을 능숙하게 수행할 수 있게 될 것입니다.

이것은 가이드 실험입니다. 학습과 실습을 돕기 위한 단계별 지침을 제공합니다.각 단계를 완료하고 실무 경험을 쌓기 위해 지침을 주의 깊게 따르세요. 과거 데이터에 따르면, 이것은 초급 레벨의 실험이며 완료율은 100%입니다.학습자들로부터 100%의 긍정적인 리뷰율을 받았습니다.

딕셔너리 생성 및 검사

이 단계에서는 딕셔너리를 생성하고 검사하는 방법을 배웁니다. 딕셔너리는 키 - 값 쌍 (key-value pairs) 의 모음이며, 여기서 각 키는 고유해야 합니다. 딕셔너리는 중괄호 {} 또는 dict() 생성자를 사용하여 생성됩니다. Python 3.7 부터 딕셔너리는 항목이 삽입된 순서를 유지합니다.

먼저, VS Code 편집기 왼쪽의 파일 탐색기에서 main.py 파일을 엽니다.

main.py에 다음 코드를 추가합니다. 이 스크립트는 딕셔너리를 생성하는 다양한 방법을 보여줍니다.

## Create an empty dictionary using curly braces
empty_dict = {}
print(f"Empty dictionary: {empty_dict}")
print(f"Type of empty_dict: {type(empty_dict)}")

## Create a dictionary with initial key-value pairs
student_info = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(f"\nStudent info: {student_info}")

## Create a dictionary using the dict() constructor with keyword arguments
student_info_kw = dict(name='Bob', age=22, major='Physics')
print(f"Student info (from keywords): {student_info_kw}")

## Create a dictionary from a list of key-value tuples
student_info_tuples = dict([('name', 'Charlie'), ('age', 28), ('major', 'Chemistry')])
print(f"Student info (from tuples): {student_info_tuples}")

코드를 추가한 후, Ctrl + S를 눌러 파일을 저장합니다.

이제 VS Code 편집기에서 터미널을 열고 (Ctrl + ~), 다음 명령을 실행하여 스크립트를 실행합니다.

python main.py

생성한 다양한 딕셔너리를 보여주는 다음 출력을 볼 수 있습니다.

Empty dictionary: {}
Type of empty_dict: <class 'dict'>

Student info: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
Student info (from keywords): {'name': 'Bob', 'age': 22, 'major': 'Physics'}
Student info (from tuples): {'name': 'Charlie', 'age': 28, 'major': 'Chemistry'}

이 단계에서는 비어 있는 딕셔너리와 초기 데이터가 있는 딕셔너리를 포함하여 Python 에서 딕셔너리를 생성하는 기본적인 방법을 배웠습니다.

딕셔너리 요소 접근 및 수정

이 단계에서는 딕셔너리 내의 요소에 접근하고 수정하는 방법을 배웁니다. 키를 대괄호 [] 안에 참조하여 값을 검색할 수 있습니다.

먼저, main.py의 이전 내용을 지웁니다. 그런 다음 파일에 다음 코드를 추가합니다. 이 스크립트는 딕셔너리 데이터에 접근하고 수정하는 방법을 보여줍니다.

## Define a sample dictionary
student_info = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(f"Original dictionary: {student_info}")

## Access elements using square brackets
student_name = student_info['name']
print(f"\nStudent Name: {student_name}")

## Using the get() method to access an element
student_age = student_info.get('age')
print(f"Student Age (using get()): {student_age}")

## The get() method can provide a default value if the key is not found
student_city = student_info.get('city', 'Not Specified')
print(f"Student City (with default): {student_city}")

## Modify the value of an existing key
print(f"\nOriginal age: {student_info['age']}")
student_info['age'] = 26
print(f"Modified age: {student_info['age']}")

print(f"\nUpdated dictionary: {student_info}")

파일을 저장 (Ctrl + S) 하고 터미널에서 스크립트를 실행합니다.

python main.py

출력 결과는 값을 검색하는 방법과 수정 후 딕셔너리가 어떻게 보이는지를 보여줍니다.

Original dictionary: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}

Student Name: Alice
Student Age (using get()): 25
Student City (with default): Not Specified

Original age: 25
Modified age: 26

Updated dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}

존재하지 않는 키에 접근하기 위해 대괄호 []를 사용하면 KeyError가 발생하지만, get() 메서드는 존재하지 않을 수 있는 키에 접근하는 더 안전한 방법을 제공한다는 점에 유의하십시오.

딕셔너리 요소 추가 및 삭제

이 단계에서는 딕셔너리에 새 요소를 추가하고 기존 요소를 삭제하는 방법을 다룹니다. 새 키에 값을 할당하여 새로운 키 - 값 쌍을 추가할 수 있습니다.

main.py의 내용을 다음 코드로 대체합니다. 이 스크립트는 추가, 업데이트, 다양한 방법으로 제거하는 등 딕셔너리 요소의 전체 수명 주기를 보여줍니다.

## Define a sample dictionary
student_info = {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
print(f"Initial dictionary: {student_info}")

## Add a new key-value pair
student_info['city'] = 'New York'
print(f"After adding 'city': {student_info}")

## Delete an element using pop()
## pop() removes the key and returns its value
removed_major = student_info.pop('major')
print(f"\nRemoved major: {removed_major}")
print(f"After pop('major'): {student_info}")

## Delete the last inserted element using popitem()
## popitem() removes and returns the (key, value) pair
removed_item = student_info.popitem()
print(f"\nRemoved item: {removed_item}")
print(f"After popitem(): {student_info}")

## Delete an element using the 'del' statement
del student_info['age']
print(f"\nAfter del student_info['age']: {student_info}")

## The clear() method removes all elements from the dictionary
student_info.clear()
print(f"After clear(): {student_info}")

파일을 저장 (Ctrl + S) 하고 스크립트를 실행합니다.

python main.py

출력 결과는 수정의 각 단계에서 딕셔너리가 어떻게 보이는지를 보여줍니다.

Initial dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
After adding 'city': {'name': 'Alice', 'age': 26, 'major': 'Computer Science', 'city': 'New York'}

Removed major: Computer Science
After pop('major'): {'name': 'Alice', 'age': 26, 'city': 'New York'}

Removed item: ('city', 'New York')
After popitem(): {'name': 'Alice', 'age': 26}

After del student_info['age']: {'name': 'Alice'}
After clear(): {}

이 단계에서는 새 요소를 추가하는 방법과 pop(), popitem(), del, clear()를 사용하여 요소를 제거하는 방법을 배웠습니다.

딕셔너리 뷰 객체 탐색

이 단계에서는 딕셔너리 뷰 객체 (dictionary view objects) 를 탐색합니다. 이는 딕셔너리의 키, 값 또는 항목 (items) 에 대한 뷰를 제공하는 동적 객체입니다. 딕셔너리에 대한 모든 변경 사항은 뷰에 즉시 반영됩니다.

main.py의 내용을 다음 코드로 대체합니다.

## Define a sample dictionary
student_info = {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
print(f"Original dictionary: {student_info}\n")

## Get the view objects
keys_view = student_info.keys()
values_view = student_info.values()
items_view = student_info.items()

print(f"Keys View: {keys_view}")
print(f"Values View: {values_view}")
print(f"Items View: {items_view}")

## Views are dynamic and reflect dictionary changes
print("\n--- Modifying Dictionary ---")
student_info['city'] = 'New York'
print(f"Dictionary after adding 'city': {student_info}")
print(f"Keys View after modification: {keys_view}")
print(f"Values View after modification: {values_view}")

## You can iterate over view objects
print("\n--- Iterating over Keys View ---")
for key in keys_view:
    print(key)

## You can convert views to other data types like lists
keys_list = list(keys_view)
print(f"\nKeys view converted to a list: {keys_list}")

파일을 저장 (Ctrl + S) 하고 스크립트를 실행합니다.

python main.py

출력 결과는 뷰 객체의 생성, 동적 특성 및 반복 (iteration) 을 보여줍니다.

Original dictionary: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}

Keys View: dict_keys(['name', 'age', 'major'])
Values View: dict_values(['Alice', 26, 'Computer Science'])
Items View: dict_items([('name', 'Alice'), ('age', 26), ('major', 'Computer Science')])

--- Modifying Dictionary ---
Dictionary after adding 'city': {'name': 'Alice', 'age': 26, 'major': 'Computer Science', 'city': 'New York'}
Keys View after modification: dict_keys(['name', 'age', 'major', 'city'])
Values View after modification: dict_values(['Alice', 26, 'Computer Science', 'New York'])

--- Iterating over Keys View ---
name
age
major
city

Keys view converted to a list: ['name', 'age', 'major', 'city']

이 단계에서는 keys(), values(), items()를 사용하여 딕셔너리 내용의 동적 뷰를 얻는 방법을 살펴보았으며, 이는 많은 프로그래밍 작업에 유용합니다.

요약

본 실습 (lab) 을 통해 Python 딕셔너리 (dictionary) 에 대한 실질적인 경험을 쌓았습니다. 중괄호 {}dict() 생성자를 사용하여 딕셔너리를 생성하는 것으로 시작했습니다. 이어서 대괄호 표기법 []get() 메서드를 사용하여 딕셔너리 요소를 접근하고 수정하는 방법을 배웠습니다. 다음으로, pop(), popitem(), del 문, clear()를 포함한 다양한 방법을 사용하여 새로운 키 - 값 쌍을 추가하고 제거하는 연습을 했습니다. 마지막으로, 동적인 딕셔너리 뷰 (keys(), values(), items()) 를 탐색하며, 이들이 딕셔너리의 변경 사항을 어떻게 반영하는지 이해하고 이를 반복 (iterate) 하는 방법을 익혔습니다.