Python 字典 (dict)

dict 是可变映射:键须可哈希,3.7+ 保留插入序;掌握读写、get、视图与常见聚合模式。

#type / concept #status / growing #tech / dev #resource / python #tech / lang / python

[!info] 关联笔记

Python 字典 (dict)

这个概念为什么出现

索引、配置、JSON 对象、聚合计数——都是“键到值”。dict 是 Python 最重要的内置映射:平均 O(1) 查找,且自 3.7 起语言保证保留插入顺序

[!abstract] 一句话理解 dict 把可哈希键映射到任意值;用 []/get 访问,视图支持遍历 keys/values/items,插入序在现代 Python 中稳定可依赖。

最小可运行示例

先把示例放进业务场景,再看代码:

场景:活动后台按渠道聚合报名并安全读配置

# channel_dict_demo.py
# 业务意图:聚合渠道计数,安全读取可选配置键。
# 教学点:
# - 创建/写入/in;
# - get 默认值 vs KeyError;
# - setdefault 与插入序。

def aggregate_channels(rows: list[dict]) -> dict[str, int]:
    counts: dict[str, int] = {}
    for row in rows:
        ch = row["channel"]
        counts[ch] = counts.get(ch, 0) + 1
    return counts


def main() -> None:
    rows = [
        {"user": "a", "channel": "wechat"},
        {"user": "b", "channel": "app"},
        {"user": "c", "channel": "wechat"},
    ]
    counts = aggregate_channels(rows)
    print("counts:", counts)
    print("keys order:", list(counts))  # 插入序

    config = {"timeout_s": 3}
    print("retries:", config.get("retries", 1))  # 缺失不炸
    # print(config["retries"])  # KeyError

    # setdefault:仅当键不存在时写入
    config.setdefault("retries", 2)
    config.setdefault("retries", 9)  # 已存在不改
    print("config:", config)


if __name__ == "__main__":
    main()

建议运行:

python channel_dict_demo.py

期望输出:

counts: {'wechat': 2, 'app': 1}
keys order: ['wechat', 'app']
retries: 1
config: {'timeout_s': 3, 'retries': 2}

结合场景再看三个关注点

  1. 聚合get 累加是清晰模式;大量计数也可用 Counter
  2. 缺失键[] 抛错,get 返回默认——API 边界要选对。
  3. 插入序让“先出现的渠道”遍历结果可预期。

核心概念与准确模型

键约束

  • 键必须可哈希且在生命周期内哈希稳定
  • 常见键:str/int/tuple(frozenset...)
  • list/dict/set 不能直接作键

视图

  • d.keys() / values() / items() 是动态视图
  • 迭代时不要增删字典结构(可改已有值,视版本/操作而定,稳妥做法是先 list)

合并

  • {**a, **b} / | / |=(3.9+)

边界情况与反直觉行为

  1. pop vs delpop 可带默认。
  2. setdefault 副作用:默认值表达式总会求值——贵对象用 if 判断。
  3. 子类/自定义映射语义可能不同。

常见误区

[!warning] 常见误区:用点语法访问 dict 错误理解:user.name 与 JS 对象一样。
正确模型:dict 用 user["name"];点语法是属性,属于对象字段。

工程实践

  • JSON object ↔ dict 是默认互转心智。
  • 配置层避免“字符串键魔法”散落,可集中常量。
  • 需要默认工厂用 collections.defaultdict

本节总结

dict 是映射与聚合的核心。先守住键可哈希与缺失键策略,再使用视图与合并语法。

自测题

  1. 为什么 list 不能当键?
  2. getsetdefault 差别?
参考答案
  1. list 可变不可哈希。
  2. get 只读默认;setdefault 在缺失时写入并返回。

延伸阅读与资料来源

资料类型支撑内容
Mapping Types — dict文档dict 语义
创建于 2026/6/6 更新于 2026/7/15