Explore Dictionary View Objects
In this step, you will explore dictionary view objects. These are dynamic objects that provide a view of a dictionary's keys, values, or items. Any changes to the dictionary are immediately reflected in the view.
Replace the content of main.py with the following code:
## 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}")
Save the file (Ctrl + S) and run the script:
python main.py
The output demonstrates the creation, dynamic nature, and iteration of view objects:
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']
This step has shown you how to use keys(), values(), and items() to get dynamic views of a dictionary's contents, which is useful for many programming tasks.