1. 认识字典
1.1 什么是字典
字典(dict)是一种保存键值对的映射。每个键(key)对应一个值(value),读取数据时通常通过键定位,而不是通过数字索引。
字典使用花括号 {} 创建,键和值之间用冒号分隔:
sample = {
"sample_id": "S01",
"group": "control",
"read_count": 1_250_000,
}
print(sample) # {'sample_id': 'S01', 'group': 'control', 'read_count': 1250000}
字典有以下特点:
- 按键访问:键用于定位数据,不使用列表式的位置索引。
- 值类型不限:字符串、数字、列表以及其他字典都可以作为值。
- 保留插入顺序:Python 会按照键加入字典的顺序保存内容,但不会自动按字母或数值排序。
1.2 创建字典的常见方式
最常见的方式是直接使用花括号。需要逐步填充数据时,可以先创建空字典;也可以使用 dict() 创建字典。
sample = {"sample_id": "S01", "group": "control"}
empty_result = {}
settings = dict(min_reads=1_000_000, normalize=True)
使用 dict() 的关键字参数写法时,键会自动成为字符串。实际编程中,花括号写法通常更直观,也能使用数字、元组等其他合法键。
1.3 键和值的规则
键必须是可哈希(hashable)的对象。可哈希对象,就是内容不会随意改变、可以被 Python 稳定识别的对象。
valid = {
"sample_id": "S01",
1: "first batch",
("control", 1): "replicate 1",
}
# invalid = {["control", 1]: "replicate 1"}
# TypeError: unhashable type: 'list'
如果创建字典时重复使用同一个键,后面的值会覆盖前面的值。
sample = {"group": "control", "group": "treated"}
print(sample) # {'group': 'treated'}
2. 读取与判断
2.1 使用方括号读取值
将键写在方括号中,可以读取对应的值。
sample = {"sample_id": "S01", "group": "control"}
print(sample["sample_id"]) # S01
print(sample["group"]) # control
如果键不存在,方括号写法会抛出 KeyError。因此,它适合读取必须存在的字段。
# print(sample["batch"]) # KeyError: 'batch'
2.2 使用 get() 安全读取
get() 适合读取可能缺失的字段。键不存在时,它会返回指定的默认值;如果没有提供默认值,则返回 None。
sample = {"sample_id": "S01", "group": "control"}
print(sample.get("group")) # control
print(sample.get("batch", "unknown")) # unknown
方括号与 get() 的选择取决于字段是否必须存在:必须存在时使用方括号,让错误尽早暴露;允许缺失时使用 get() 并给出合适的默认值。
2.3 使用 in 判断键是否存在
in 和 not in 默认检查的是字典的键。
sample = {"sample_id": "S01", "read_count": 1_250_000}
if"read_count"in sample:
print("Read count is available.") # Read count is available.
print("group"notin sample) # True
如果要检查某个值,需要显式使用 values()。
print("S01"in sample) # False:检查键
print("S01"in sample.values()) # True:检查值
2.4 获取键值对数量
len() 返回字典中键值对的数量。
sample = {"sample_id": "S01", "group": "control", "batch": "B01"}
print(len(sample)) # 3
3. 添加、修改与批量更新
3.1 添加新的键值对
给一个不存在的键赋值,就会向字典中添加新的键值对。
sample = {"sample_id": "S01", "group": "control"}
sample["batch"] = "B01"
sample["qc_pass"] = True
print(sample)
3.2 修改已有值
给已经存在的键重新赋值,会替换原来的值。
sample = {"sample_id": "S01", "qc_status": "pending"}
sample["qc_status"] = "passed"
print(sample["qc_status"]) # passed
字典中的值也可以参与计算或条件判断,再将结果写回字典。
sample = {
"sample_id": "S01",
"read_count": 1_250_000,
"coverage": "pending",
}
if sample["read_count"] >= 2_000_000:
coverage = "high"
elif sample["read_count"] >= 1_000_000:
coverage = "medium"
else:
coverage = "low"
sample["coverage"] = coverage
print(sample["coverage"]) # medium
3.3 从空字典逐步构建数据
当字段需要根据计算结果逐项生成时,可以从空字典开始。
summary = {}
summary["total_samples"] = 24
summary["passed_samples"] = 21
summary["pass_rate"] = summary["passed_samples"] / summary["total_samples"]
print(summary) # {'total_samples': 24, 'passed_samples': 21, 'pass_rate': 0.875}
3.4 使用 update() 批量更新
update() 可以一次添加或修改多个键值对。新键会被添加,已有键会被覆盖。
sample = {"sample_id": "S01", "group": "control"}
sample.update({
"group": "treated",
"batch": "B02",
"qc_pass": True,
})
print(sample) # {'sample_id': 'S01', 'group': 'treated', 'batch': 'B02', 'qc_pass': True}
update() 会直接修改原字典,并返回 None,因此不要把它的返回值当成更新后的字典。
4. 删除键值对
4.1 使用 del 删除
知道键名且不需要继续使用被删除的值时,可以使用 del。
sample = {"sample_id": "S01", "group": "control", "notes": "repeat"}
del sample["notes"]
print(sample) # {'sample_id': 'S01', 'group': 'control'}
如果键不存在,del 会抛出 KeyError。
4.2 使用 pop() 删除并取得值
pop() 会删除指定键,并返回被删除的值。
sample = {"sample_id": "S01", "group": "control", "notes": "repeat"}
removed_notes = sample.pop("notes")
print(removed_notes) # repeat
print(sample) # {'sample_id': 'S01', 'group': 'control'}
在参数中提供默认值后,即使键不存在也不会报错。
removed_notes = sample.pop("notes", None)
print(removed_notes) # None
4.3 使用 clear() 清空字典
clear() 会删除全部键值对,但保留原来的字典对象。
cache = {"S01": "passed", "S02": "failed"}
cache.clear()
print(cache) # {}
| | |
|---|
del data[key] | | |
data.pop(key) | | |
data.clear() | | |
5. 遍历字典
5.1 遍历所有键值对
items() 会提供每一组键和值,通常使用两个变量接收。
sample = {
"sample_id": "S01",
"group": "control",
"qc_pass": True,
}
for key, value in sample.items():
print(f"{key}: {value}")
# sample_id: S01
# group: control
# qc_pass: True
5.2 遍历所有键
直接遍历字典时,默认取得键;使用 keys() 的结果相同。
for key in sample:
print(key)
# sample_id
# group
# qc_pass
for key in sample.keys():
print(key)
# sample_id
# group
# qc_pass
如果显示时需要固定的排序,可以使用 sorted()。
for key in sorted(sample):
print(key)
# group
# qc_pass
# sample_id
5.3 遍历所有值
values() 只提供值,不包含对应的键。
sample_groups = {
"S01": "control",
"S02": "treated",
"S03": "control",
}
for group in sample_groups.values():
print(group)
# control
# treated
# control
需要去除重复值时,可以使用 set();如果还需要稳定的显示顺序,可以再用 sorted()。
unique_groups = sorted(set(sample_groups.values()))
print(unique_groups) # ['control', 'treated']
6. 嵌套
6.1 列表中的字典
当多个对象拥有相同字段时,可以把多个字典放入列表。
samples = [
{"sample_id": "S01", "group": "control"},
{"sample_id": "S02", "group": "treated"},
]
for sample in samples:
print(f"{sample['sample_id']}: {sample['group']}")
# S01: control
# S02: treated
6.2 字典中的列表
一个键需要对应多个值时,可以将列表作为字典的值。
experiment = {
"name": "marker validation",
"genes": ["CD3D", "CD4", "CD8A"],
}
for gene in experiment["genes"]:
print(gene)
# CD3D
# CD4
# CD8A
6.3 字典中的字典
需要通过唯一标识快速查找多个对象时,可以在字典中嵌套字典。
samples = {
"S01": {"group": "control", "qc_pass": True},
"S02": {"group": "treated", "qc_pass": False},
}
for sample_id, sample_info in samples.items():
print(f"{sample_id}: {sample_info['group']}")
print(f"QC passed: {sample_info['qc_pass']}")
# S01: control
# QC passed: True
# S02: treated
# QC passed: False
7. 字典推导式与复制
7.1 使用字典推导式生成字典
字典推导式可以根据一个可迭代对象快速生成键值对,基本结构如下:
{key_expression: value_expression for item in iterable}
例如,生成数字及其平方:
squares = {number: number ** 2for number in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
也可以加入简单条件进行筛选。
qc_results = {"S01": True, "S02": False, "S03": True}
passed = {sample_id: status for sample_id, status in qc_results.items() if status}
print(passed) # {'S01': True, 'S03': True}
如果转换逻辑包含多层条件,建议使用普通 for 循环,通常更容易阅读。
8. 常见错误与实践建议
8.1 常见错误
| | |
|---|
KeyError | | |
TypeError: unhashable type | | |
| | |
dictionary changed size during iteration | | |
| | |
| | |
不要在遍历原字典时直接改变其大小。需要删除部分键时,可以遍历键的列表副本。
results = {"S01": 0.92, "S02": 0.41, "S03": 0.88}
for sample_id in list(results): # list(results) 先复制一份所有键
if results[sample_id] < 0.5:
del results[sample_id]
print(results) # {'S01': 0.92, 'S03': 0.88}
8.2 编写清晰字典代码的建议
- 使用含义明确的名称,如
sample_info、qc_results、analysis_settings。 - 必填字段使用方括号读取,可选字段使用
get() 并设置合理默认值。 - 一次修改多个字段时使用
update(),同时留意已有键是否会被覆盖。 - 嵌套层级不宜过深;访问表达式越来越长时,应考虑拆分结构。
- 需要固定展示顺序时显式使用
sorted(),不要把插入顺序误认为排序结果。
9. 常用操作速查
| |
|---|
| data = {}、 dict() |
| data[key] |
| data.get(key, default) |
| key in data |
| len(data) |
| data[key] = value |
| data.update(other) |
| del data[key] |
| data.pop(key, default) |
| data.clear() |
| for key, value in data.items(): |
| for key in data: |
| for value in data.values(): |
| {key: value for item in iterable} |
| data.copy() |