当前位置: 首页 > java >正文

【Python基础】Python中字典知识点梳理

Python中字典知识点梳理

前言

字典(Dictionary)是Python中最重要的数据结构之一,它以键值对(key-value)的形式存储数据,具有高效的查找、插入和删除操作。本文将全面梳理Python字典的核心知识点,帮助大家深入理解和熟练运用字典。

1. 字典基础概念

1.1 什么是字典

字典是一种可变的、无序的(Python 3.7+保持插入顺序)数据类型,使用花括号 {} 表示,内部存储键值对。

# 创建字典的几种方式
dict1 = {'name': '张三', 'age': 25, 'city': '北京'}
dict2 = dict(name='李四', age=30, city='上海')
dict3 = dict([('name', '王五'), ('age', 35)])
dict4 = {}  # 空字典

1.2 字典的特点

  • 键唯一性:每个键在字典中只能出现一次
  • 键不可变:键必须是不可变类型(字符串、数字、元组等)
  • 值可变:值可以是任意数据类型
  • 无序性:Python 3.7之前字典无序,3.7+保持插入顺序

2. 字典的基本操作

2.1 访问元素

student = {'name': '小明', 'age': 20, 'grade': 85}# 通过键访问值
print(student['name'])  # 小明
print(student.get('age'))  # 20
print(student.get('height', 170))  # 170(默认值)

2.2 添加和修改元素

student = {'name': '小明', 'age': 20}# 添加新元素
student['grade'] = 85
student['city'] = '深圳'# 修改现有元素
student['age'] = 21print(student)  # {'name': '小明', 'age': 21, 'grade': 85, 'city': '深圳'}

2.3 删除元素

student = {'name': '小明', 'age': 20, 'grade': 85, 'city': '深圳'}# 使用del删除
del student['city']# 使用pop()删除并返回值
age = student.pop('age')
print(age)  # 20# 使用popitem()删除最后一个键值对
last_item = student.popitem()
print(last_item)  # ('grade', 85)# 清空字典
student.clear()
print(student)  # {}

3. 字典的常用方法

3.1 获取键、值和键值对

student = {'name': '小明', 'age': 20, 'grade': 85}# 获取所有键
keys = student.keys()
print(list(keys))  # ['name', 'age', 'grade']# 获取所有值
values = student.values()
print(list(values))  # ['小明', 20, 85]# 获取所有键值对
items = student.items()
print(list(items))  # [('name', '小明'), ('age', 20), ('grade', 85)]

3.2 字典合并和更新

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'b': 20, 'e': 5}# 使用update()方法
dict1.update(dict2)
print(dict1)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}# 使用**操作符(Python 3.5+)
merged = {**dict1, **dict3}
print(merged)  # {'a': 1, 'b': 20, 'c': 3, 'd': 4, 'e': 5}# 使用|操作符(Python 3.9+)
result = dict1 | dict3
print(result)  # {'a': 1, 'b': 20, 'c': 3, 'd': 4, 'e': 5}

3.3 字典复制

original = {'a': 1, 'b': [2, 3, 4]}# 浅复制
shallow_copy = original.copy()
copy_dict = dict(original)# 深复制
import copy
deep_copy = copy.deepcopy(original)# 修改原字典中的列表
original['b'].append(5)
print(shallow_copy)  # {'a': 1, 'b': [2, 3, 4, 5]} - 受影响
print(deep_copy)     # {'a': 1, 'b': [2, 3, 4]} - 不受影响

4. 字典推导式

字典推导式是创建字典的简洁方式,语法类似列表推导式。

# 基本语法:{key_expr: value_expr for item in iterable}# 示例1:创建平方字典
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}# 示例2:字符串长度字典
words = ['apple', 'banana', 'cherry']
lengths = {word: len(word) for word in words}
print(lengths)  # {'apple': 5, 'banana': 6, 'cherry': 6}# 示例3:带条件的字典推导式
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)  # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}# 示例4:转换现有字典
original = {'a': 1, 'b': 2, 'c': 3}
upper_keys = {k.upper(): v * 2 for k, v in original.items()}
print(upper_keys)  # {'A': 2, 'B': 4, 'C': 6}

5. 字典的遍历

5.1 遍历键

student = {'name': '小明', 'age': 20, 'grade': 85}# 方法1:直接遍历字典
for key in student:print(key, student[key])# 方法2:使用keys()方法
for key in student.keys():print(key, student[key])

5.2 遍历值

for value in student.values():print(value)

5.3 遍历键值对

# 推荐方式
for key, value in student.items():print(f"{key}: {value}")

6. 嵌套字典

实际应用中,字典经常嵌套使用,形成复杂的数据结构。

# 学生信息系统
students = {'student1': {'name': '张三','age': 20,'scores': {'math': 90, 'english': 85, 'chinese': 88}},'student2': {'name': '李四','age': 21,'scores': {'math': 95, 'english': 90, 'chinese': 92}}
}# 访问嵌套数据
print(students['student1']['name'])  # 张三
print(students['student1']['scores']['math'])  # 90# 遍历嵌套字典
for student_id, info in students.items():print(f"学生ID: {student_id}")print(f"姓名: {info['name']}")print("成绩:")for subject, score in info['scores'].items():print(f"  {subject}: {score}")print()

7. 字典的高级应用

7.1 defaultdict

from collections import defaultdict# 自动创建默认值
dd = defaultdict(list)
dd['fruits'].append('apple')
dd['fruits'].append('banana')
print(dd)  # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})# 统计字符出现次数
text = "hello world"
char_count = defaultdict(int)
for char in text:char_count[char] += 1
print(dict(char_count))  # {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

7.2 Counter

from collections import Counter# 计数器
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counter = Counter(words)
print(counter)  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(counter.most_common(2))  # [('apple', 3), ('banana', 2)]

7.3 OrderedDict

from collections import OrderedDict# 有序字典(Python 3.7+普通字典也保持顺序)
od = OrderedDict()
od['first'] = 1
od['second'] = 2
od['third'] = 3# 移动到末尾
od.move_to_end('first')
print(od)  # OrderedDict([('second', 2), ('third', 3), ('first', 1)])

8. 字典的性能特点

8.1 时间复杂度

  • 查找:O(1) 平均情况,O(n) 最坏情况
  • 插入:O(1) 平均情况
  • 删除:O(1) 平均情况
  • 遍历:O(n)

8.2 内存优化

# Python 3.6+字典更节省内存
import sys# 比较不同数据结构的内存使用
data_list = [('a', 1), ('b', 2), ('c', 3)] * 1000
data_dict = {f'key_{i}': i for i in range(3000)}print(f"列表内存: {sys.getsizeof(data_list)} bytes")
print(f"字典内存: {sys.getsizeof(data_dict)} bytes")

9. 实际应用场景

9.1 配置管理

# 应用配置
config = {'database': {'host': 'localhost','port': 5432,'username': 'admin','password': 'secret'},'cache': {'redis_host': '127.0.0.1','redis_port': 6379},'debug': True
}def get_config(key_path):"""获取嵌套配置值"""keys = key_path.split('.')value = configfor key in keys:value = value[key]return valueprint(get_config('database.host'))  # localhost

9.2 缓存实现

class SimpleCache:def __init__(self, max_size=100):self.cache = {}self.max_size = max_sizedef get(self, key):return self.cache.get(key)def set(self, key, value):if len(self.cache) >= self.max_size:# 删除最旧的项(简单实现)oldest_key = next(iter(self.cache))del self.cache[oldest_key]self.cache[key] = valuedef clear(self):self.cache.clear()# 使用示例
cache = SimpleCache(max_size=3)
cache.set('user:1', {'name': '张三', 'age': 25})
cache.set('user:2', {'name': '李四', 'age': 30})
print(cache.get('user:1'))  # {'name': '张三', 'age': 25}

9.3 数据分组

# 按条件分组数据
students = [{'name': '张三', 'age': 20, 'grade': 'A'},{'name': '李四', 'age': 21, 'grade': 'B'},{'name': '王五', 'age': 20, 'grade': 'A'},{'name': '赵六', 'age': 22, 'grade': 'C'}
]# 按年龄分组
age_groups = {}
for student in students:age = student['age']if age not in age_groups:age_groups[age] = []age_groups[age].append(student)print(age_groups)
# {20: [{'name': '张三', 'age': 20, 'grade': 'A'}, {'name': '王五', 'age': 20, 'grade': 'A'}], 
#  21: [{'name': '李四', 'age': 21, 'grade': 'B'}], 
#  22: [{'name': '赵六', 'age': 22, 'grade': 'C'}]}

10. 常见陷阱和注意事项

10.1 可变对象作为默认值

# 错误示例
def add_student(name, scores={}):scores[name] = 0return scoresresult1 = add_student('张三')
result2 = add_student('李四')
print(result1)  # {'张三': 0, '李四': 0} - 意外!# 正确做法
def add_student(name, scores=None):if scores is None:scores = {}scores[name] = 0return scores

10.2 字典遍历时修改

# 错误示例
data = {'a': 1, 'b': 2, 'c': 3}
for key in data:if data[key] % 2 == 0:del data[key]  # RuntimeError!# 正确做法
data = {'a': 1, 'b': 2, 'c': 3}
keys_to_delete = [key for key, value in data.items() if value % 2 == 0]
for key in keys_to_delete:del data[key]

10.3 键的类型问题

# 注意键的类型
data = {1: 'one', '1': 'string one'}
print(data[1])    # 'one'
print(data['1'])  # 'string one'
print(len(data))  # 2 - 不同类型的键被视为不同

总结

字典是Python中功能强大且使用频繁的数据结构,掌握其核心概念和常用操作对于Python编程至关重要。本文从基础概念到高级应用,全面梳理了字典的知识点:

  1. 基础操作:创建、访问、修改、删除
  2. 常用方法:keys()、values()、items()、update()等
  3. 高级特性:字典推导式、嵌套字典、特殊字典类型
  4. 性能特点:时间复杂度和内存优化
  5. 实际应用:配置管理、缓存、数据分组等
  6. 注意事项:常见陷阱和最佳实践

熟练掌握这些知识点,能够帮助我们在实际开发中更高效地使用字典,写出更优雅和高性能的Python代码。


希望这篇文章对大家学习Python字典有所帮助!如果有任何问题或建议,欢迎在评论区交流讨论。

http://www.xdnf.cn/news/13697.html

相关文章:

  • 预训练CNN网络的迁移学习(MATLAB例)
  • 在线机考|2025年华为暑期实习春招秋招编程题(最新)——第1题_物流运输
  • 【leetcode】104. 二叉树的最大深度
  • Spring上下文模块设计
  • 高防IP是怎么防御的?高防IP的防御步骤又有哪些?
  • SKE 与 SM2、SM3、SM4 的关系 ,SPDM协议的详细解析
  • 【Bitcoin基础】比特币的地址格式有哪些?如何应用?
  • 如何正确评估服务器CPU/内存/IO利用率 (性能过剩or瓶颈)
  • Spring涉及的设计模式以及实际使用场景(含代码)
  • 汽车电池智造关键一环!DeviceNet转Modbus RTU网关的实战突围
  • pod重启次数过多怎么排查
  • 数据结构 散列表 学习 2025年6月12日15:30:48
  • 旧物新生,绿色领航——旧物二手回收软件开启资源循环新篇章
  • 超维智联 质胜千里:晨控 RFID 驱动汽车后视镜智造跃迁
  • 离婚房产分割折价款计算的司法裁判策略
  • 13.15 LLaMA 3+LangChain重构语法学习:可视化语法树+智能纠错让效率翻倍!
  • VScode使用npm启动项目以及npm install ,npm start报错问题处理
  • ThreadLocal原理及内存泄漏分析
  • EVNIA 27M2N3500UK显示器荣膺TÜV莱茵圆偏光认证,树立健康显示新标杆
  • Web 架构之 Kubernetes 弹性伸缩策略设计
  • CHI协议验证中的异常及边界验证
  • 输电线防山火在线监测装置:科技赋能电网安全防线
  • 泛微OAe9-自定义资源看板
  • 纯血HarmonyOS ArKTS NETX 5 打造小游戏实践:大鱼吃小鱼(附源文件)
  • G1周打卡——GAN入门
  • 考研系列—408真题操作系统篇(2015-2019)
  • 煜邦智源SNEC全球首发智慧储能系统,携手德国莱茵TÜV加速全球化布局
  • Java 中使用 Redis 注解版缓存——补充
  • Qt Creator 从入门到项目实战
  • 「pandas 与 numpy」数据分析与处理全流程【数据分析全栈攻略:爬虫+处理+可视化+报告】