You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python嵌套字典按页码匹配书名函数的错误排查

问题解决:根据页码匹配书籍章节名称

需求说明

我有一个嵌套字典存储书籍的章节名称和对应页码,需要编写一个Python函数:

  • 第一个参数是待搜索的字典
  • 第二个参数是字符串类型的页码
  • 函数需要遍历字典,打印所有页码与传入参数匹配的章节名称

字典示例

text = {
    1: {
        1: {"ch.name": "The Boy Who Lived", "pages": "146"},
        2: {"ch.name": "The Vanishing Glass", "pages": "126"},
    },
    2: {
        1: {"ch.name": "The Worst Birthday", "pages": "129"},
        2: {"ch.name": "Dobby's Warning", "pages": "125"},
    },
}

错误代码及问题

我尝试了以下代码:

def Name(text,pages):
    pages=pages
    for key1, value1 in text.items():
        for key2, value2 in value1.items():
            output = key1,key2,value2['ch.name'],value2['pages']
            output
            if pages is pages:
                print(f"{value2['ch.name']}")


Name(text, '125')

运行结果打印了所有章节:

The Boy Who Lived
The Vanishing Glass
The Worst Birthday
Dobby's Warning

但预期结果应该只有页码为125的章节:

Dobby's Warning

问题分析

代码里的判断条件if pages is pages:完全无效——这是同一个变量和自身比较,永远为True,所以所有章节都会被打印。正确的逻辑应该是判断当前章节的页码是否和传入的参数相等。

另外注意:字符串比较值要用==,而不是is。is是比较对象的内存地址,短字符串可能因Python缓存机制看似相等,但对于任意字符串场景,用==比较值才是可靠的做法。

修正后的代码

def find_chapter_by_page(text, target_page):
    for book_part in text.values():
        for chapter in book_part.values():
            if chapter['pages'] == target_page:
                print(chapter['ch.name'])

find_chapter_by_page(text, '125')

运行后输出符合预期:

Dobby's Warning

内容的提问来源于stack exchange,提问作者TTT_LT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 12:01:02