딕셔너리 뷰 객체 탐색
이 단계에서는 딕셔너리 뷰 객체 (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()를 사용하여 딕셔너리 내용의 동적 뷰를 얻는 방법을 살펴보았으며, 이는 많은 프로그래밍 작업에 유용합니다.