介绍
在这个 Lab 中,你将获得关于 Python 字典的实践经验,字典是一种用于将数据存储为键值对(key-value pairs)的重要数据结构。你将学习如何创建和检查字典、访问和修改其元素、添加和删除条目,以及使用字典视图对象(dictionary view objects)。完成这个 Lab 后,你将熟练掌握执行常见的字典操作。
在这个 Lab 中,你将获得关于 Python 字典的实践经验,字典是一种用于将数据存储为键值对(key-value pairs)的重要数据结构。你将学习如何创建和检查字典、访问和修改其元素、添加和删除条目,以及使用字典视图对象(dictionary view objects)。完成这个 Lab 后,你将熟练掌握执行常见的字典操作。
在这个步骤中,你将学习如何创建和检查字典。字典是键值对(key-value pairs)的集合,其中每个键都必须是唯一的。字典使用花括号 {} 或 dict() 构造函数创建。自 Python 3.7 起,字典会保持项被插入的顺序。
首先,从 VS Code 编辑器左侧的文件资源管理器中打开 main.py 文件。
将以下代码添加到 main.py 中。此脚本演示了创建字典的各种方法。
## 使用花括号创建空字典
empty_dict = {}
print(f"Empty dictionary: {empty_dict}")
print(f"Type of empty_dict: {type(empty_dict)}")
## 创建带有初始键值对的字典
student_info = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(f"\nStudent info: {student_info}")
## 使用关键字参数(keyword arguments)的 dict() 构造函数创建字典
student_info_kw = dict(name='Bob', age=22, major='Physics')
print(f"Student info (from keywords): {student_info_kw}")
## 从键值对元组(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 中之前的内容。然后,将以下代码添加到文件中。此脚本演示了如何访问和修改字典数据。
## 定义一个示例字典
student_info = {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
print(f"Original dictionary: {student_info}")
## 使用方括号访问元素
student_name = student_info['name']
print(f"\nStudent Name: {student_name}")
## 使用 get() 方法访问元素
student_age = student_info.get('age')
print(f"Student Age (using get()): {student_age}")
## 如果找不到键,get() 方法可以提供一个默认值
student_city = student_info.get('city', 'Not Specified')
print(f"Student City (with default): {student_city}")
## 修改现有键的值
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 的内容替换为以下代码。此脚本演示了字典元素的完整生命周期:以各种方式添加、更新和删除它们。
## 定义一个示例字典
student_info = {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
print(f"Initial dictionary: {student_info}")
## 添加一个新的键值对
student_info['city'] = 'New York'
print(f"After adding 'city': {student_info}")
## 使用 pop() 删除一个元素
## pop() 会移除键并返回其值
removed_major = student_info.pop('major')
print(f"\nRemoved major: {removed_major}")
print(f"After pop('major'): {student_info}")
## 使用 popitem() 删除最后插入的元素
## popitem() 会移除并返回 (键,值) 对
removed_item = student_info.popitem()
print(f"\nRemoved item: {removed_item}")
print(f"After popitem(): {student_info}")
## 使用 'del' 语句删除一个元素
del student_info['age']
print(f"\nAfter del student_info['age']: {student_info}")
## clear() 方法会从字典中移除所有元素
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)。这些是动态对象,它们提供了对字典的键、值或项的视图。对字典的任何更改都会立即反映在视图中。
将 main.py 的内容替换为以下代码:
## 定义一个示例字典
student_info = {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}
print(f"Original dictionary: {student_info}\n")
## 获取视图对象
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}")
## 视图是动态的,会反映字典的变化
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}")
## 你可以遍历视图对象
print("\n--- Iterating over Keys View ---")
for key in keys_view:
print(key)
## 你可以将视图转换为其他数据类型,如列表
keys_list = list(keys_view)
print(f"\nKeys view converted to a list: {keys_list}")
保存文件(Ctrl + S)并运行脚本:
python main.py
输出演示了视图对象的创建、动态特性和迭代:
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() 来获取字典内容(contents)的动态视图,这对于许多编程任务非常有用。
在此次实验(Lab)中,你获得了使用 Python 字典的实践经验。你从使用花括号 {} 和 dict() 构造函数创建字典开始。然后,你学习了使用方括号表示法 [] 和 get() 方法来访问和修改字典元素。接着,你练习了添加新的键值对,并使用各种方法(包括 pop()、popitem()、del 语句和 clear())来删除它们。最后,你探索了动态字典视图(keys()、values() 和 items()),理解了它们如何反映字典中的变化以及如何遍历它们。