字典就像智能快递柜:
模块 | 功能 | 时间复杂度 |
---|---|---|
查找 | get操作 | O(1) |
插入 | dict[key] = value | O(1) |
删除 | del dict[key] | O(1) |
遍历 | items() | O(n) |
特性 | 字典 | 列表 | 集合 |
---|---|---|---|
存储方式 | 键值对 | 索引 | 唯一值 |
查找速度 | O(1) | O(n) | O(1) |
内存占用 | 高 | 中 | 低 |
# Python 3.7+ 原生支持
from collections import defaultdict, OrderedDict
# 创建字典
user = {"name": "Alice", "age": 30, "email": "[email protected]"}
# 访问元素
print(user["name"]) # Alice
print(user.get("phone", "N/A")) # 安全访问:N/A
# 快速生成字典
squares = {x: x**2 for x in range(5)}
# {0:0, 1:1, 2:4, 3:9, 4:16}
# 使用defaultdict
word_counts = defaultdict(int)
for word in ["a", "b", "a"]:
word_counts[word] += 1 # 自动初始化0
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = {**dict1, **dict2} # {'a':1, 'b':2}
# 保持插入顺序
od = OrderedDict()
od["z"] = 3
od["a"] = 1
print(list(od.keys())) # ['z', 'a']
original = {"a":1, "b":2}
inverted = {v:k for k,v in original.items()}
employees = {
"Alice": {"age":30, "dept":"IT"},
"Bob": {"age":25, "dept":"HR"}
}
print(employees["Alice"]["dept"]) # IT
keys_view = user.keys() # 动态视图
user["phone"] = "123456"
print(keys_view) # 包含新键phone
config = {
"debug": True,
"database": {
"host": "localhost",
"port": 3306
}
}
def connect(**kwargs):
print(f"Connecting to {kwargs.get('host')}")
params = {"host":"localhost", "port":3306}
connect(**params) # 解包传参
# 案例3输出:
defaultdict(, {'a': 2, 'b': 1})
# 案例5输出:
['z', 'a']
# 案例10输出:
Connecting to localhost
操作 | 字典(ms) | 列表(ms) | 优势比 |
---|---|---|---|
查找 | 0.01 | 1200 | 120000x |
插入 | 0.02 | 0.03 | 1.5x |
删除 | 0.015 | 1100 | 73000x |
安全访问键值
value = my_dict.get("key", default_value)
使用字典推导式
{k:v for k,v in iterable if condition}
配置默认字典
from collections import defaultdict
d = defaultdict(list)
合并字典新语法
merged = dict1 | dict2 # Python 3.9+
字典解包传参
func(**{"param": value})
内存优化存储
from __future__ import annotations # 延迟类型注解
不可变字典
from types import MappingProxyType
read_only = MappingProxyType(original)
类型提示
from typing import Dict, TypedDict
class User(TypedDict):
name: str
age: int
有序字典选择
# Python 3.7+普通字典已有序
哈希优化键设计
# 使用不可变类型作为键
key = (1, "a") # 元组作为键
可变对象作为键
{["a"]: 1} # TypeError
遍历时修改字典
for k in d:
del d[k] # RuntimeError
误用浅拷贝
d = {"a": [1]}
d2 = d.copy()
d2["a"].append(2) # 影响原字典
忽略哈希冲突
# 自定义对象需实现__hash__和__eq__
键不存在异常
print(d["missing"]) # KeyError
错误更新方式
d.update(1, 2) # 应传入字典或可迭代对象
内存泄漏
# 循环引用导致无法回收
d = {}
d["self"] = d
视图对象误解
keys = d.keys()
d["new"] = 1
list(keys) # 包含new键
无序假设错误
# Python 3.6之前字典无序
类型混淆
d = {1: "a", "1": "b"} # 不同键类型
字典内容检查
print(json.dumps(d, indent=2)) # 格式化输出
哈希值查看
print(hash(key)) # 检查键的哈希值
内存分析
import sys
print(sys.getsizeof(d)) # 查看字典内存占用