1、创建字典
student_score = {"xiaohong": 85, "xiaogang": 91, "xiaohuang": 88}
2、访问字典元素
score = student_score["xiaohong"]
2.1、使用 get 方法获取值(避免 key 不存在时抛出异常)
score = student_score.get("xiaojin", 0)
3、存在 -> 修改;不存在 -> 添加
student_score["xiaohong"] = 90
3.1、使用 setdefault 方法(如果 key 不存在,则设置默认值)
score = student_score.setdefault("xiaojin", 95)
3.2、update 字典
new_scores = {"xiaomei": 89, "xiaoli": 87}
student_score.update(new_scores)
4、删除元素
del student_score["xiaogang"]
5、检查 key 是否存在
if "xiaojin" in student_score:
print("xiaojin is in student_score")
6、获取所有 key
keys = student_score.keys()
7、获取所有值
values = student_score.values()
8、获取所有键值对
items = student_score.items()
key, value = student_score.items()
8.1、遍历
for key, value in student_score.items():
print(f"{key}: {value}")
9、清空字典
student_score.clear()
10、复制字典
student_score_copy = student_score.copy()
11、弹出元素
score = student_score.pop("xiaohuang", None)
11.1、 弹出任意元素
key, value = student_score.popitem()
12、字典推导式
squared_scores = {key: value**2 for key, value in student_score.items()}
13、从键值对序列创建字典
pairs = [("xiaohong", 85), ("xiaogang", 91)]
student_score_from_pairs = dict(pairs)