Python 字典方法
字典是Python中最有用、最灵活的数据结构之一,它允许我们通过键(key)而不是索引来存储和检索数据。了解Python字典的各种方法对于有效利用这一强大的数据结构至关重要。本文将全面介绍Python字典的各种方法及其使用方式。
什么是Python字典?
字典是一种可变的、无序的数据集合,用来存储键值对(key-value pairs)。每个键都是唯一的,并与一个值相关联。
python
# 创建字典的基本语法
my_dict = {
"name": "Alice",
"age": 25,
"is_student": True
}
字典的创建方法
1. 使用花括号 {}
python
# 使用花括号创建字典
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
输出:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
2. 使用 dict()
构造函数
python
# 使用dict()构造函数
car = dict(brand="Ford", model="Mustang", year=1964)
print(car)
输出:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
3. 使用 dict.fromkeys()
方法
python
# 使用dict.fromkeys()创建具有相同值的字典
keys = ["a", "b", "c"]
value = 0
my_dict = dict.fromkeys(keys, value)
print(my_dict)
输出:
{'a': 0, 'b': 0, 'c': 0}
访问字典元素的方法
1. 使用键 []
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(car["model"])
输出:
Mustang
2. 使用 get()
方法
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(car.get("model"))
# 使用默认值
print(car.get("price", "Not Available"))
输出:
Mustang
Not Available
提示
get()
方法是访问字典值的安全方式。当键不存在时,使用方括号 []
会引发 KeyError,而 get()
会返回 None 或指定的默认值。
修改字典的方法
1. 添加或更新元素
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
# 添加新元素
car["color"] = "red"
# 更新已有元素
car["year"] = 2020
print(car)
输出:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'color': 'red'}
2. update()
方法
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
car.update({"color": "red", "year": 2020})
print(car)
输出:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'color': 'red'}
删除字典元素的方法
1. pop()
方法
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964, "color": "red"}
removed_value = car.pop("color")
print(f"Removed value: {removed_value}")
print(f"Updated dictionary: {car}")
输出:
Removed value: red
Updated dictionary: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
2. popitem()
方法
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
removed_item = car.popitem() # 在Python 3.7+中移除最后添加的项
print(f"Removed item: {removed_item}")
print(f"Updated dictionary: {car}")
输出:
Removed item: ('year', 1964)
Updated dictionary: {'brand': 'Ford', 'model': 'Mustang'}
3. del
关键字
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
del car["model"]
print(car)
输出:
{'brand': 'Ford', 'year': 1964}
4. clear()
方法
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
car.clear()
print(car)
输出:
{}
字典遍历方法
1. 遍历所有键
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
# 方法1:直接遍历
for key in car:
print(key)
# 方法2:使用keys()
for key in car.keys():
print(key)
输出:
brand
model
year
brand
model
year
2. 遍历所有值
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
for value in car.values():
print(value)
输出:
Ford
Mustang
1964
3. 遍历键值对
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
for key, value in car.items():
print(f"{key}: {value}")
输出:
brand: Ford
model: Mustang
year: 1964
其他常用字典方法
1. copy()
- 创建字典的浅复制
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
car_copy = car.copy()
car_copy["year"] = 2020
print(f"Original: {car}")
print(f"Copy: {car_copy}")
输出:
Original: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Copy: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
2. setdefault()
- 如果键不存在则设置默认值
python
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
# 键存在的情况
value1 = car.setdefault("model", "Bronco")
# 键不存在的情况
value2 = car.setdefault("color", "red")
print(f"Value1: {value1}")
print(f"Value2: {value2}")
print(f"Updated dictionary: {car}")
输出:
Value1: Mustang
Value2: red
Updated dictionary: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
实际应用案例
案例1: 学生成绩管理系统
python
# 创建学生成绩字典
student_scores = {
"Alice": {"Math": 85, "Science": 90, "English": 88},
"Bob": {"Math": 78, "Science": 85, "English": 92},
"Charlie": {"Math": 92, "Science": 88, "English": 75}
}
# 添加新学生
student_scores["David"] = {"Math": 80, "Science": 82, "English": 85}
# 更新某个学生的成绩
student_scores["Alice"]["Math"] = 88
# 计算每个学生的平均分
for student, subjects in student_scores.items():
total = sum(subjects.values())
average = total / len(subjects)
print(f"{student}'s average score: {average:.2f}")
# 找出数学成绩最高的学生
max_math_score = 0
best_math_student = ""
for student, subjects in student_scores.items():
if subjects["Math"] > max_math_score:
max_math_score = subjects["Math"]
best_math_student = student
print(f"Best math student: {best_math_student} with score {max_math_score}")
输出:
Alice's average score: 88.67
Bob's average score: 85.00
Charlie's average score: 85.00
David's average score: 82.33
Best math student: Charlie with score 92
案例2: 商品库存管理
python
# 初始库存
inventory = {
"apple": {"price": 0.5, "quantity": 100},
"banana": {"price": 0.3, "quantity": 150},
"orange": {"price": 0.6, "quantity": 80}
}
# 添加新商品
inventory["grape"] = {"price": 0.8, "quantity": 60}
# 更新价格
inventory["apple"]["price"] = 0.55
# 销售一些水果
def sell_fruit(fruit_name, amount):
if fruit_name in inventory:
if inventory[fruit_name]["quantity"] >= amount:
inventory[fruit_name]["quantity"] -= amount
revenue = amount * inventory[fruit_name]["price"]
print(f"Sold {amount} {fruit_name}(s) for ${revenue:.2f}")
return True
else:
print(f"Error: Not enough {fruit_name}s in stock")
return False
else:
print(f"Error: {fruit_name} not in inventory")
return False
# 计算库存总价值
def calculate_total_value():
total_value = 0
for fruit, details in inventory.items():
fruit_value = details["price"] * details["quantity"]
total_value += fruit_value
return total_value
# 测试功能
sell_fruit("apple", 20)
sell_fruit("banana", 30)
sell_fruit("orange", 100) # 库存不足
print("\nCurrent inventory:")
for fruit, details in inventory.items():
print(f"{fruit}: price=${details['price']}, quantity={details['quantity']}")
print(f"\nTotal inventory value: ${calculate_total_value():.2f}")
输出:
Sold 20 apple(s) for $11.00
Sold 30 banana(s) for $9.00
Error: Not enough oranges in stock
Current inventory:
apple: price=$0.55, quantity=80
banana: price=$0.3, quantity=120
orange: price=$0.6, quantity=80
grape: price=$0.8, quantity=60
Total inventory value: $140.00
总结
Python字典是一种功能强大的数据结构,提供了许多有用的方法来管理键值对数据。在本教程中,我们学习了:
- 创建字典的不同方法
- 访问、修改和删除字典元素
- 遍历字典的键、值和键值对
- 其他实用的字典方法如
copy()
和setdefault()
- 字典在实际应用中的使用案例
通过掌握这些方法,你可以有效地使用字典来解决各种编程问题,特别是在需要通过键快速查找和修改数据的场景中。
练习
-
创建一个字典,存储5个国家及其首都,然后编写代码完成以下任务:
- 添加一个新的国家和首都
- 更新一个已有国家的首都
- 删除一个国家及其首都
- 打印所有国家及其首都
-
编写一个程序,统计文本中每个单词出现的次数,并按出现频率排序。
-
创建一个简单的通讯录应用,支持添加、查找、更新和删除联系人信息。
额外资源
Happy coding!