Python 中的元组(tuple) 和 字典(dict) 是两种非常核心且常用的内置数据类型。下面用清晰、结构化的方式给你介绍它们的定义、特点和最常用的基本用法(基于 Python 3.12+ 最新特性,2026 年视角无重大语法变化)。
1. 元组(tuple)
核心特点
- 有序(有索引,从 0 开始)
- 不可变(immutable):创建后不能增删改元素(但如果元素本身是可变对象如 list,里面的内容仍可改)
- 允许重复元素
- 用小括号
()表示(最常见写法)
创建方式
# 常用写法
t1 = (1, 2, 3)
t2 = 10, 20, 30 # 括号可以省略(推荐只在简单场景省略)
t3 = () # 空元组
t4 = (88,) # 只有一个元素的元组,必须加逗号!否则会被认为是普通括号
t5 = tuple([1, 2, 3]) # 从可迭代对象转换
t6 = tuple("hello") # ('h','e','l','l','o')
t7 = 1, # (1,) 单元素也必须加逗号
最容易犯错的点:
a = (5) # 这是 int 5,不是 tuple!
b = (5,) # 这才是只有一个元素的 tuple
基本操作
t = (10, 20, 30, 40, 50, 20)
# 1. 取值 / 切片(和列表一样)
print(t[0]) # 10
print(t[-1]) # 50(倒数第一个)
print(t[1:4]) # (20, 30, 40)
print(t[::2]) # (10, 30, 50) 步长2
# 2. 查找
print(t.index(20)) # 1 (返回第一个匹配的索引)
print(t.count(20)) # 2 (出现次数)
# 3. 长度
print(len(t)) # 6
# 4. 成员判断
print(30 in t) # True
print(99 not in t) # True
# 5. 拆包(非常常用!)
a, b, c = (100, 200, 300) # a=100, b=200, c=300
x, *y, z = (1, 2, 3, 4, 5) # x=1, y=[2,3,4], z=5 (* 收集多余元素)
print(x, y, z) # 1 [2, 3, 4] 5
元组 vs 列表 对比(面试/工作中常问)
| 特性 | tuple(元组) | list(列表) |
|---|---|---|
| 是否可变 | 不可变 | 可变 |
| 性能 | 更快(内存更省) | 稍慢 |
| 安全性 | 更高(数据不变) | 可被意外修改 |
| 典型用途 | 固定配置、函数多返回值、作为 dict 的 key | 需要增删改的场景 |
| 可哈希 | 是(可做 dict key / set 元素) | 否 |
2. 字典(dict)
核心特点(Python 3.7+ 之后)
- 无序 → 有序:3.7 起插入顺序保证有序(最重要变化!)
- 键值对(key-value)存储
- 键必须唯一、键必须可哈希(不可变类型:str、int、float、tuple、frozenset 等)
- 值可以是任意类型
- 用大括号
{}表示
创建方式
# 最常用
d1 = {"name": "Alice", "age": 18, "city": "Shanghai"}
# 空字典
d2 = {}
d3 = dict()
# 从键值对列表/元组创建
d4 = dict([("a", 1), ("b", 2)])
d5 = dict(name="Bob", score=95, city="Beijing") # 关键字参数方式
# 字典推导式(很常用)
d6 = {i: i**2 for i in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
基本操作(最常用写法)
student = {"name": "小明", "age": 20, "score": 88}
# 1. 取值(三种方式)
print(student["name"]) # 小明
print(student.get("age")) # 20
print(student.get("gender", "未知")) # 未知(键不存在返回默认值)
# 2. 新增 / 修改
student["gender"] = "男" # 新增
student["score"] = 95 # 修改
student.setdefault("class", "一班") # 如果键不存在则添加,有则不动
# 3. 删除
del student["age"] # 删除指定键
student.pop("score") # 删除并返回被删除的值
student.pop("height", None) # 键不存在不报错
student.clear() # 清空整个字典
# 4. 判断键是否存在
print("name" in student) # True / False
print("height" not in student) # True
# 5. 获取所有键/值/键值对
print(student.keys()) # dict_keys([...])
print(student.values()) # dict_values([...])
print(student.items()) # dict_items([('name','小明'), ...])
# 6. 遍历(最常用三种方式)
for k in student:
print(k, student[k])
for k, v in student.items():
print(f"{k} → {v}")
# 7. 更新(合并字典)
d1 = {"a": 1, "b": 2}
d2 = {"b": 99, "c": 3}
d1.update(d2) # d1 变成 {'a':1, 'b':99, 'c':3}
Python 3.9+ 新增好用的运算符(非常推荐)
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
# 合并(不修改原字典)
d3 = d1 | d2 # {'a':1, 'b':3, 'c':4}
# 原地更新
d1 |= d2 # d1 变成合并后的结果
总结一句话对比
- 元组 tuple:像不可变的列表,主要用于固定、不变的数据集合、函数返回多个值、做字典的 key
- 字典 dict:键值映射神器,查找速度极快(接近 O(1)),现代 Python 项目中使用频率最高的数据结构之一
如果你正在学 Python,建议优先熟练掌握:
元组拆包 + 字典的 get()/setdefault()/items() 遍历 + 字典推导式 + | 合并运算符
有哪部分还想看更详细的示例(比如嵌套、排序、defaultdict、Counter 等进阶用法)?直接告诉我~