Python基础教程(Python 字典)
在 Python 里,字典(Dictionary)是一种功能强大且用途广泛的数据结构,下面从多个方面对其进行详细讲解。
1. 字典的定义与创建
字典是一种可变的、无序的数据类型,它以键 - 值对(key - value pairs)的形式存储数据。键必须是不可变的数据类型(如字符串、数字、元组),且在一个字典中键是唯一的,而值可以是任意数据类型。
- 直接使用花括号创建:
# 创建一个空字典
empty_dict = {}
# 创建包含键值对的字典
student = {
'name': 'Alice',
'age': 20,
'grades': [85, 90, 92]
}
- 使用
dict()函数创建:
# 通过传入键值对参数创建
person = dict(name='Bob', occupation='Engineer')
# 通过包含元组的列表创建
colors = dict([('red', 1), ('green', 2), ('blue', 3)])
2. 字典的基本操作
- 访问元素:通过键来访问对应的值。如果键不存在,会引发
KeyError异常。可以使用get()方法来避免这种异常,当键不存在时,get()方法会返回None或指定的默认值。
student = {'name': 'Alice', 'age': 20}
print(student['name']) # 输出: Alice
print(student.get('grades', 'No grades available')) # 输出: No grades available
- 修改元素:直接通过键来修改对应的值。
student = {'name': 'Alice', 'age': 20}
student['age'] = 21
print(student) # 输出: {'name': 'Alice', 'age': 21}
- 添加元素:如果键不存在,直接赋值就会添加新的键值对。
student = {'name': 'Alice', 'age': 20}
student['city'] = 'New York'
print(student) # 输出: {'name': 'Alice', 'age': 20, 'city': 'New York'}
- 删除元素:使用
del语句或pop()方法。del语句直接删除指定键的键值对,pop()方法删除指定键的键值对并返回该值。
student = {'name': 'Alice', 'age': 20, 'city': 'New York'}
del student['city']
print(student) # 输出: {'name': 'Alice', 'age': 20}
age = student.pop('age')
print(age) # 输出: 20
print(student) # 输出: {'name': 'Alice'}
3. 字典的常用方法
keys()方法:返回一个包含字典所有键的视图对象。可以将其转换为列表等其他可迭代对象。
student = {'name': 'Alice', 'age': 20}
keys = student.keys()
print(list(keys)) # 输出: ['name', 'age']
values()方法:返回一个包含字典所有值的视图对象。
student = {'name': 'Alice', 'age': 20}
values = student.values()
print(list(values)) # 输出: ['Alice', 20]
items()方法:返回一个包含字典所有键值对的视图对象,每个键值对以元组形式表示。
student = {'name': 'Alice', 'age': 20}
items = student.items()
print(list(items)) # 输出: [('name', 'Alice'), ('age', 20)]
update()方法:用于将一个字典的键值对更新到另一个字典中。如果有相同的键,会覆盖原有的值。
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1) # 输出: {'a': 1, 'b': 3, 'c': 4}
clear()方法:清空字典中的所有键值对。
student = {'name': 'Alice', 'age': 20}
student.clear()
print(student) # 输出: {}
4. 字典的遍历
- 遍历键:
student = {'name': 'Alice', 'age': 20}
for key in student.keys():
print(key)
- 遍历值:
student = {'name': 'Alice', 'age': 20}
for value in student.values():
print(value)
- 遍历键值对:
student = {'name': 'Alice', 'age': 20}
for key, value in student.items():
print(key, ':', value)
5. 字典的嵌套
字典中可以嵌套其他字典、列表等数据结构。
students = {
'student1': {
'name': 'Alice',
'age': 20
},
'student2': {
'name': 'Bob',
'age': 21
}
}
print(students['student1']['name']) # 输出: Alice
6. 字典的复制
- 浅拷贝:使用
copy()方法进行浅拷贝,新字典和原字典是不同的对象,但如果值是可变对象,它们会共享这些可变对象。
dict1 = {'a': [1, 2]}
dict2 = dict1.copy()
dict2['a'].append(3)
print(dict1) # 输出: {'a': [1, 2, 3]}
- 深拷贝:使用
copy模块的deepcopy()函数进行深拷贝,会递归地复制所有对象,新字典和原字典完全独立。
import copy
dict1 = {'a': [1, 2]}
dict2 = copy.deepcopy(dict1)
dict2['a'].append(3)
print(dict1) # 输出: {'a': [1, 2]}
通过以上内容,你可以全面了解 Python 字典的各种特性和操作,从而在编程中灵活运用字典来处理数据。
浙公网安备 33010602011771号