一、字典的创建
- 字典的字面量创建:
my_dict = {"name": "John Doe", "age": 30, "city": "New York"}
- 字典的内置函数创建:
my_dict = dict(name="John Doe", age=30, city="New York")
- 字典的推导式创建:
my_dict = {key: value for key, value in zip(["name", "age", "city"], ["John Doe", 30, "New York"])}
二、字典的修改
- 添加键值对:
my_dict["job"] = "Software Engineer"
- 修改键值对:
my_dict["age"] = 31
- 删除键值对:
del my_dict["city"]
三、字典的查找
- 通过键获取值:
value = my_dict["name"]
- 使用
get()
方法获取值(如果键不存在,返回默认值):
value = my_dict.get("phone", "Not provided")
- 检查键是否存在:
if "email" in my_dict:
# 键存在,执行某些操作
四、字典的遍历
- 遍历键:
for key in my_dict:
print(key)
- 遍历键和值:
for key, value in my_dict.items():
print(key, value)
- 遍历键和值(使用
dict.values()
和dict.keys()
):
for value in my_dict.values():
print(value)
for key in my_dict.keys():
print(key)
五、其他技巧
- 字典的合并:
my_dict1 = {"name": "John Doe", "age": 30}
my_dict2 = {"city": "New York", "job": "Software Engineer"}
my_dict3 = {**my_dict1, **my_dict2}
- 字典的复制:
my_dict_copy = my_dict.copy()
- 字典的排序:
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
掌握这些技巧,可以帮助您更加高效地使用 Python 字典,提高代码的质量和性能。