跳到主内容

LangChain Python

最后更新: 2026-10-11

1. 映射

字典(dictionary)用于保存一组「键:值」关系。知道一个键,就可以找到它对应的值,因此字典特别适合表示用户信息、配置项、接口请求和模型参数。

使用花括号创建字典,键和值之间使用冒号,多个键值对之间使用逗号:

create.py
1
user = {
2
"name": "小明",
3
"age": 18,
4
"is_member": True,
5
}
6
7
print(user)

字典的键必须是唯一且可哈希的类型,常见的是字符串、整数和元组;列表和另一个字典不能作为键。值可以是任意类型:

key-value.py
1
data = {
2
"name": "小明",
3
1: "第一个版本",
4
(2026, 8): "发布日期",
5
}
6
7
print(data)

如果重复写入同一个键,后面的值会覆盖前面的值:

duplicate-key.py
1
scores = {
2
"小明": 82,
3
"小明": 95,
4
}
5
6
print(scores) # {'小明': 95}

Python 3.7 及以上版本会保留字典键的插入顺序,但字典的核心仍然是键值查找,不应该把它当成列表使用位置索引。

也可以使用 dict() 创建字典:

dict-function.py
1
user = dict(name="小明", age=18)
2
3
print(user) # {'name': '小明', 'age': 18}

2. 读取

使用方括号和键可以读取字典中的值:

access.py
1
user = {
2
"name": "小明",
3
"age": 18,
4
}
5
6
print(user["name"]) # 小明
7
print(user["age"]) # 18

如果键不存在,方括号读取会抛出 KeyError:

missing-key.py
1
user = {"name": "小明"}
2
3
# print(user["email"]) # KeyError

不确定键是否存在时,可以先使用 in,或者使用 get():

get.py
01
user = {"name": "小明"}
02
03
if "email" in user:
04
print(user["email"])
05
06
email = user.get("email")
07
city = user.get("city", "未知城市")
08
09
print(email) # None
10
print(city) # 未知城市

get(key, default) 在键存在时返回原值,在键不存在时返回默认值,而且不会修改字典。处理请求参数或外部数据时,get() 通常比直接使用方括号更安全。

需要区分「键不存在」和「键存在但值为 None」时,不能只判断 get() 的结果:

none-value.py
1
data = {"result": None}
2
3
if "result" in data:
4
print("result 这个键存在")
5
6
print(data.get("result")) # None

3. 修改

给一个不存在的键赋值,就会新增键值对;给已有键赋值,就会更新它的值:

assign.py
1
user = {"name": "小明"}
2
3
user["age"] = 18
4
user["name"] = "小明同学"
5
6
print(user)

update() 可以一次添加或更新多个键值对:

update.py
1
user = {
2
"name": "小明",
3
"age": 18,
4
}
5
6
user.update({"age": 19, "city": "上海"})
7
8
print(user)

setdefault() 在键不存在时写入默认值,在键已经存在时保留原值:

setdefault.py
1
user = {"name": "小明"}
2
3
user.setdefault("tags", [])
4
user["tags"].append("Python")
5
6
print(user) # {'name': '小明', 'tags': ['Python']}

两个字典可以使用 | 合并,右侧字典的值会覆盖左侧同名键。|= 会把合并结果写回左侧字典:

merge.py
1
default_config = {"timeout": 30, "retries": 2}
2
custom_config = {"timeout": 60}
3
4
config = default_config | custom_config
5
default_config |= {"debug": True}
6
7
print(config) # {'timeout': 60, 'retries': 2}
8
print(default_config) # {'timeout': 30, 'retries': 2, 'debug': True}

删除字典中的数据有几种方式:

delete.py
01
user = {
02
"name": "小明",
03
"age": 18,
04
"city": "上海",
05
}
06
07
del user["age"]
08
city = user.pop("city", "未知城市")
09
last_item = user.popitem()
10
11
print(city) # 上海
12
print(last_item) # ('name', '小明')
13
print(user) # {}

del 删除指定键,但键不存在时会抛出 KeyError;pop() 删除指定键并返回值,还可以提供默认值;popitem() 删除并返回最后插入的键值对。需要清空所有数据时使用 clear():

clear.py
1
data = {"name": "小明", "age": 18}
2
data.clear()
3
4
print(data) # {}

4. 遍历

直接遍历字典时,循环变量得到的是键:

keys.py
1
user = {
2
"name": "小明",
3
"age": 18,
4
}
5
6
for key in user:
7
print(key)

使用 keys() 可以明确表达「遍历所有键」,使用 values() 可以只遍历值:

keys-values.py
1
scores = {"小明": 82, "小红": 95, "小李": 58}
2
3
for name in scores.keys():
4
print(name)
5
6
for score in scores.values():
7
print(score)

最常用的方式是使用 items() 同时得到键和值:

items.py
1
scores = {"小明": 82, "小红": 95, "小李": 58}
2
3
for name, score in scores.items():
4
if score >= 60:
5
print(f"{name}:通过")

in 默认检查的是键,不是值:

membership.py
1
scores = {"小明": 82, "小红": 95}
2
3
print("小明" in scores) # True
4
print(82 in scores) # False
5
print(82 in scores.values()) # True

遍历字典时不要一边遍历字典本身,一边直接新增或删除键,否则可能抛出 RuntimeError。如果确实需要修改键,可以先遍历 list(data) 得到一个独立的键列表:

safe-update.py
1
data = {"a": 1, "b": 2, "c": 3}
2
3
for key in list(data):
4
if data[key] < 2:
5
del data[key]
6
7
print(data) # {'b': 2, 'c': 3}

5. 嵌套

字典的值可以是另一个字典或列表,因此可以表达层次化数据:

nested.py
01
user = {
02
"profile": {
03
"name": "小明",
04
"city": "上海",
05
},
06
"tags": ["Python", "AI"],
07
}
08
09
print(user["profile"]["name"]) # 小明
10
print(user["tags"][0]) # Python

访问多层结构时,任意一层缺少键都可能抛出 KeyError。数据来自接口或用户输入时,可以逐层使用 get(),或者先进行结构校验:

nested-get.py
1
data = {"profile": {"name": "小明"}}
2
3
profile = data.get("profile", {})
4
city = profile.get("city", "未知城市")
5
6
print(city) # 未知城市

列表中保存多个字典是接口数据中很常见的结构:

list-of-dicts.py
01
users = [
02
{"name": "小明", "active": True},
03
{"name": "小红", "active": False},
04
{"name": "小李", "active": True},
05
]
06
07
active_names = [
08
user["name"]
09
for user in users
10
if user["active"]
11
]
12
13
print(active_names) # ['小明', '小李']

6. 实例

FastAPI 请求体和 LangChain 消息通常都可以先用字典表达。下面模拟一个聊天请求:

chat-request.py
01
request = {
02
"model": "deepseek-chat",
03
"messages": [
04
{"role": "user", "content": "请介绍一下 Python。"},
05
],
06
"temperature": 0.2,
07
}
08
09
request["messages"].append({
10
"role": "system",
11
"content": "请使用中文回答。",
12
})
13
14
for message in request["messages"]:
15
print(f"{message['role']}:{message['content']}")

这个结构中,外层字典保存模型配置和消息列表,消息列表中的每一项又是一个字典。实际项目里,Pydantic 模型会负责校验这类请求,但理解字典结构仍然是读懂请求数据的基础。

字典也常用于统计分类结果:

count-tags.py
1
tags = ["python", "ai", "python", "web", "ai"]
2
counts = {}
3
4
for tag in tags:
5
counts[tag] = counts.get(tag, 0) + 1
6
7
print(counts) # {'python': 2, 'ai': 2, 'web': 1}

counts.get(tag, 0) 在第一次遇到标签时返回 0,之后每次遇到同一个标签就把计数加 1。这是字典在实际数据处理中非常常见的模式。

字典可以转换为 JSON 字符串,方便在接口或文件中传输:

json-data.py
1
import json
2
3
data = {
4
"name": "小明",
5
"topics": ["Python", "LangChain"],
6
}
7
8
text = json.dumps(data, ensure_ascii=False)
9
print(text)

7. 在线字典实验

使用字典处理一份用户信息,再合并更新字段、读取嵌套资料和统计标签次数。本例只处理数据结构,文章中的聊天请求也是结构模拟,不需要模型密钥。

案例项目文件
使用上下方向键浏览目录,左右方向键展开或收起,Enter 或空格切换展开状态。
    • main.pyFastAPI 接口与请求参数校验
    • dictionaries_demo.py本篇主题的 Python 实验
    • pyproject.toml项目与基础依赖配置
    • .python-version本机 Python 3.12
    • .gitignore忽略环境与生成文件
    • README.md运行步骤与边界说明

7.1 完整案例代码

main.py 提供接口,dictionaries_demo.py 执行实验。下面展示的代码与在线编辑器的初始文件来自同一份源码;修改编辑器中的文件后,保存并重新运行,接口就会使用修改后的内容。

main.py
01
from typing import Annotated
02
03
from fastapi import FastAPI, Request
04
from fastapi.exceptions import RequestValidationError
05
from fastapi.responses import JSONResponse
06
from pydantic import BaseModel, Field, FiniteFloat
07
08
from dictionaries_demo import build_report
09
10
app = FastAPI()
11
Tag = Annotated[str, Field(max_length=100)]
12
Scalar = str | int | FiniteFloat | bool | None
13
14
@app.exception_handler(RequestValidationError)
15
async def invalid_request(request: Request, error: RequestValidationError) -> JSONResponse:
16
# 不回传原始输入,避免非有限数让校验错误响应也无法序列化。
17
detail = [{"type": item["type"], "loc": item["loc"], "msg": item["msg"]}
18
for item in error.errors()]
19
return JSONResponse(status_code=422, content={"detail": detail})
20
21
class DictionaryRequest(BaseModel):
22
user: dict[str, Scalar] = Field(default_factory=dict, max_length=30)
23
updates: dict[str, Scalar] = Field(default_factory=dict, max_length=30)
24
profile: dict[str, str] = Field(default_factory=dict, max_length=30)
25
tags: list[Tag] = Field(default_factory=list, max_length=100)
26
27
@app.post("/dictionaries")
28
async def dictionaries(request: DictionaryRequest) -> dict[str, object]:
29
report = build_report(request.user, request.updates, request.profile, request.tags)
30
print(f"合并后的用户:{report['updated']}")
31
print(f"标签计数:{report['tag_counts']}")
32
print(f"缺省城市:{report['nested']['city']}")
33
return report
34
dictionaries_demo.py
01
import json
02
03
def build_report(
04
user: dict, updates: dict, profile: dict[str, str], tags: list[str]
05
) -> dict[str, object]:
06
updated = user.copy()
07
updated.update(updates)
08
updated.setdefault("city", "未知城市")
09
merged = user | updates
10
11
counts = {}
12
for tag in tags:
13
counts[tag] = counts.get(tag, 0) + 1
14
15
# 删除操作使用另一份字典,保留前面的更新结果。
16
remaining = updated.copy()
17
removed_city = remaining.pop("city", "未知城市")
18
last_item = remaining.popitem() if remaining else None
19
nested = {"profile": profile.copy(), "tags": tags.copy()}
20
21
# 元组键不是 JSON 对象键,只返回查询得到的值。
22
release_names = {(2026, 8): "发布日期"}
23
return {
24
"original": user.copy(),
25
"updated": updated,
26
"merged": merged,
27
"lookup": {"email": updated.get("email"), "has_email_key": "email" in updated},
28
"keys": list(updated.keys()),
29
"values": list(updated.values()),
30
"items": [{"key": key, "value": value} for key, value in updated.items()],
31
"deletion": {"removed_city": removed_city,
32
"last_item": list(last_item) if last_item is not None else None,
33
"remaining": remaining},
34
"nested": {"data": nested, "city": nested["profile"].get("city", "未知城市")},
35
"tag_counts": counts,
36
"tuple_key_lookup": release_names[(2026, 8)],
37
"json_text": json.dumps(updated, ensure_ascii=False),
38
}
39
40
if __name__ == "__main__":
41
report = build_report({"name": "小明", "age": 18}, {"age": 19, "city": "上海"},
42
{"name": "小明"}, ["python", "ai", "python", "web", "ai"])
43
print(json.dumps(report, ensure_ascii=False, indent=2))
44

7.2 运行与观察

打开本篇在线案例,点击运行并等待环境就绪。案例预览默认选择 POST,地址为:

code.ts
1
/dictionaries

请求体已填好,可以直接发送:

code.ts
01
{
02
"user": {
03
"name": "小明",
04
"age": 18
05
},
06
"updates": {
07
"age": 19,
08
"city": "上海"
09
},
10
"profile": {
11
"name": "小明"
12
},
13
"tags": [
14
"python",
15
"ai",
16
"python",
17
"web",
18
"ai"
19
]
20
}

默认响应中,original.age 仍是 18,updated.age 与 merged.age 都是 19,updated.city 为 "上海"。tag_counts 是 {"python": 2, "ai": 2, "web": 1};profile 没有 city,nested.city 会返回 "未知城市"。

日志会打印对应的关键操作结果。在 updates 中把 age 改成 20,再发送观察覆盖结果。在 user 中添加 "email": null,可看到 lookup.email 仍为 null,但 has_email_key 变为 true,区分缺失键与空值。将 tags 改成 [],计数字典会变为空对象。修改 dictionaries_demo.py 的默认城市后,保存并重新运行。

user 和 updates 仅接受 JSON 标量值,数值中的 Infinity、NaN 等非有限值会在入口返回 HTTP 422;profile 要求字符串键值的对象,传入 null 或错误层级会返回 HTTP 422,不会执行到多层 get() 时才报错。空字典可以正常处理,popitem() 前会判断是否为空。字典视图明确转成列表或记录,元组键字典只返回查询结果,避免 JSON 无法表示原键。每次请求都会复制后再更新,不会改写下一次请求的初始数据。

7.3 在本机继续运行

本案例只使用标准库、FastAPI 与 Pydantic,不需要模型密钥。下载并解压 ZIP,进入项目目录后执行:

code.ts
1
uv run python dictionaries_demo.py
2
uv run fastapi dev main.py

第一条直接在终端打印实验结果;第二条启动 FastAPI。打开 http://127.0.0.1:8000/docs,选择 POST /dictionaries,填写同样的参数即可发起请求。本机使用 Python 3.12,浏览器使用当前 Pyodide 版本,通过 HTTPX ASGITransport 执行接口,不启动电脑上的 8000 端口。

本篇的代码、日志、Git 配置与 PI Agent 对话使用独立工作区;同站 Python 依赖缓存可以复用。本机配置文件、忽略规则和 README 都包含在项目中,可以在文件目录里查看、编辑和下载。

正在验证登录状态
请稍候,验证完成后将继续显示文章内容

此段落已有评论,按 Enter 查看评论及回复列表。

评论-

文章反应
评论与回复

连接 GitHub 后查看和发表评论,也可在 GitHub 查看公开讨论。

添加评论
    即时渲染