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

Python字典如何存储对应文件名作为值而非数字序号

代码修改方案

你只需要调整2处逻辑即可实现需求,修改后的完整代码如下:

# 注意列表内的字符串需要加引号,修正原语法错误
file_list = ['hello.txt', 'bye.txt', 'test.txt']
file_contents = ['text of hello', 'text of bye', 'text of test']
# 提前定义你要匹配的关键词列表,原代码缺失该变量定义
words = ['test', 'text']
res_dict = {}
for i in range(len(file_list)):
    check = file_contents[i].lower()
    for item in words:
        if item in check:
            if item not in res_dict:
                res_dict[item] = []
            # 核心修改:把原来追加序号i+1,改成追加对应下标的文件名
            res_dict[item].append(file_list[i])

res_dict = {k: list(set(v)) for k, v in res_dict.items()}
print(res_dict)

修改说明

  • 原代码dict[item].append(i+1)是将遍历序号作为值存入,替换为file_list[i]即可直接存入对应的文件名
  • 不建议用dict作为变量名,这是Python内置类型的关键字,重命名为res_dict避免冲突
  • 原代码的file_list内的文件名没有加引号,属于语法错误,补充后可正常运行
  • 原代码缺失words变量定义,补充你需要匹配的关键词列表即可正常运行

运行上述代码后输出为:

{'test': ['test.txt'], 'text': ['hello.txt', 'bye.txt', 'test.txt']}

完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:18:03