大家好,欢迎来到IT知识分享网。
昨天,我们学习了元组(Tuple),了解了不可变数据结构的特性。今天,我们将学习字典(Dictionary) — Python中最强大的数据结构之一,它使用键值对来存储和组织数据。
字典在Python中无处不在,从配置设置到API响应,从数据库记录到缓存系统,都离不开字典。
今天您将学习什么
- 什么是字典以及如何创建字典
- 字典的基本操作:增删改查
- 字典的常用方法
- 字典的遍历和嵌套
- 真实世界示例:用户管理系统、配置管理
什么是字典?
字典是Python中的一种无序、可变的数据结构,用花括号{}表示。它存储键值对,其中每个键都是唯一的,用于访问对应的值。
基本语法:
# 创建空字典 empty_dict = {} # 创建包含键值对的字典 person = { "name": "Alice", "age": 25, "city": "New York" } # 使用dict()构造函数 person2 = dict(name="Bob", age=30, city="London")
1. 访问字典元素
使用方括号访问
person = {"name": "Alice", "age": 25, "city": "New York"} print(person["name"]) # Alice print(person["age"]) # 25
使用get()方法(推荐)
# get()方法更安全,如果键不存在不会报错 print(person.get("name")) # Alice print(person.get("email")) # None print(person.get("email", "Not found")) # Not found
➕ 2. 添加和修改元素
person = {"name": "Alice", "age": 25} # 添加新键值对 person["city"] = "New York" person["email"] = "" # 修改现有值 person["age"] = 26 print(person) # {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': ''}
➖ 3. 删除元素
del 语句
person = {"name": "Alice", "age": 25, "city": "New York"} del person["age"] print(person) # {'name': 'Alice', 'city': 'New York'}
pop() 方法
person = {"name": "Alice", "age": 25, "city": "New York"} removed_age = person.pop("age") print(removed_age) # 25 print(person) # {'name': 'Alice', 'city': 'New York'}
popitem() 方法
person = {"name": "Alice", "age": 25, "city": "New York"} key, value = person.popitem() # 删除并返回最后一个键值对 print(f"删除的键值对:{key} = {value}")
4. 检查键是否存在
person = {"name": "Alice", "age": 25} # 使用 in 操作符 print("name" in person) # True print("email" in person) # False # 使用 keys() 方法 print("name" in person.keys()) # True
5. 遍历字典
遍历键
person = {"name": "Alice", "age": 25, "city": "New York"} for key in person: print(key) # 或者 for key in person.keys(): print(key)
遍历值
for value in person.values(): print(value)
遍历键值对
for key, value in person.items(): print(f"{key}: {value}")
6. 字典的常用方法
update() – 合并字典
dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} dict1.update(dict2) print(dict1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
clear() – 清空字典
person = {"name": "Alice", "age": 25} person.clear() print(person) # {}
copy() – 复制字典
person = {"name": "Alice", "age": 25} person_copy = person.copy() print(person_copy) # {'name': 'Alice', 'age': 25}
️ 7. 嵌套字典
字典可以嵌套,创建复杂的数据结构:
students = { "001": { "name": "Alice", "age": 20, "grades": {"math": 85, "english": 90, "science": 88} }, "002": { "name": "Bob", "age": 22, "grades": {"math": 92, "english": 85, "science": 90} } } # 访问嵌套数据 print(students["001"]["name"]) # Alice print(students["001"]["grades"]["math"]) # 85 print(students["002"]["grades"]["english"]) # 85
真实世界示例1:用户管理系统
# 用户管理系统 users = {} def add_user(user_id, name, email, age): users[user_id] = { "name": name, "email": email, "age": age, "created_at": "2025-07-07" } print(f"用户 {name} 已添加") def get_user(user_id): return users.get(user_id, "用户不存在") def update_user(user_id, kwargs): if user_id in users: users[user_id].update(kwargs) print(f"用户 {user_id} 信息已更新") else: print("用户不存在") def delete_user(user_id): if user_id in users: name = users[user_id]["name"] del users[user_id] print(f"用户 {name} 已删除") else: print("用户不存在") def list_users(): if users: print("所有用户:") for user_id, user_info in users.items(): print(f"ID: {user_id}, 姓名: {user_info['name']}, 邮箱: {user_info['email']}") else: print("没有用户") # 使用示例 add_user("001", "Alice", "", 25) add_user("002", "Bob", "", 30) list_users() update_user("001", age=26) delete_user("002") list_users()
⚙️ 真实世界示例2:配置管理系统
# 应用配置管理 app_config = { "database": { "host": "localhost", "port": 5432, "name": "myapp", "user": "admin", "password": "secret123" }, "server": { "host": "0.0.0.0", "port": 8000, "debug": True }, "features": { "enable_cache": True, "enable_logging": True, "max_connections": 100 } } def get_config(section, key=None): """获取配置值""" if section not in app_config: return None if key is None: return app_config[section] return app_config[section].get(key) def update_config(section, key, value): """更新配置值""" if section in app_config and key in app_config[section]: app_config[section][key] = value print(f"配置已更新:{section}.{key} = {value}") else: print("配置项不存在") def show_database_config(): """显示数据库配置""" db_config = get_config("database") print("数据库配置:") for key, value in db_config.items(): if key == "password": print(f" {key}: {'*' * len(value)}") else: print(f" {key}: {value}") # 使用示例 print("数据库主机:", get_config("database", "host")) print("服务器端口:", get_config("server", "port")) update_config("server", "port", 9000) show_database_config()
真实世界示例3:单词计数器
def count_words(text): """统计文本中单词的出现次数""" words = text.lower().split() word_count = {} for word in words: # 移除标点符号 word = word.strip(".,!?;:") if word: word_count[word] = word_count.get(word, 0) + 1 return word_count def get_most_common_words(word_count, n=5): """获取最常见的n个单词""" sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True) return sorted_words[:n] # 使用示例 text = "Python is a great programming language. Python is easy to learn and Python is powerful." word_count = count_words(text) print("单词统计:") for word, count in word_count.items(): print(f" {word}: {count}") print("\n最常见的单词:") most_common = get_most_common_words(word_count, 3) for word, count in most_common: print(f" {word}: {count}")
字典的最佳实践
✅ 推荐做法:
- 使用有意义的键名
- 使用get()方法避免KeyError
- 使用字典推导式创建字典
- 合理使用嵌套字典
❌ 避免的做法:
- 使用可变对象作为键
- 过度嵌套(超过3层)
- 使用过长的键名
字典与其他数据结构的转换
# 列表转字典 pairs = [("a", 1), ("b", 2), ("c", 3)] dict_from_list = dict(pairs) print(dict_from_list) # {'a': 1, 'b': 2, 'c': 3} # 字典转列表 person = {"name": "Alice", "age": 25} items_list = list(person.items()) keys_list = list(person.keys()) values_list = list(person.values())
回顾
今天您学习了:
- 如何创建和访问字典
- 字典的基本操作:增删改查
- 字典的遍历和嵌套
- 字典的常用方法
- 真实世界应用:用户管理、配置管理、单词统计
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/188996.html