1. 引言Python字典是一种灵活且强大的数据结构,用于存储键值对。在编程中,经常需要向字典中添加新的键值对。本文将详细介绍如何在Python中添加新键值对,并提供一些实用技巧。2. 创建字典在Py...
Python字典是一种灵活且强大的数据结构,用于存储键值对。在编程中,经常需要向字典中添加新的键值对。本文将详细介绍如何在Python中添加新键值对,并提供一些实用技巧。
在Python中,可以使用以下两种方法创建字典:
# 方法一:使用花括号
student_info = {}
# 方法二:使用dict()函数
student_info = dict(name="Alice", age=20, courses=["Math", "Physics"])student_info["email"] = "alice@example.com"additional_info = {"email": "alice@example.com", "phone": "123456789"}
student_info.update(additional_info)student_info = { "name": "Alice", "age": 20, "courses": ["Math", "Physics"], **additional_info
}student_info["age"] = 21del student_info["email"]age = student_info.pop("age")# 遍历键
for key in student_info.keys(): print(key)
# 遍历键值对
for key, value in student_info.items(): print(f"{key}: {value}")def get_student_info(student_id): return student_info.get(student_id, "Student not found.")
print(get_student_info("B123")) # Student not found.new_student_info = {k: v.upper() for k, v in student_info.items()}掌握如何在Python字典中添加新键值对对于编程新手和专业人士都是非常重要的。本文介绍了创建字典、添加新键值对、修改现有键的值、删除键值对、遍历字典以及一些实用技巧。通过学习这些内容,你可以更加熟练地使用Python字典,提高编程效率。