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

Python遍历字典列表取filename加载图片存入列表的for循环写法

正确实现代码

原参考循环的错误是直接把索引值i传给了load_img,没有取出对应位置的文件名。修正时只需要通过索引拿到列表内对应字典,再取filename键的值传入即可,另外原代码range(len(a_list)漏了右括号,需要补上避免语法错误。

完整可运行代码如下:

# 提前导入load_img方法,根据你的实际环境调整导入路径即可
from tensorflow.keras.preprocessing.image import load_img

final_list = []

a_list = [
    {'convertedDate': '2022-02-14 13:23:01.560000', 'filename': '20220214T132301560.jpg'},
    {'convertedDate': '2022-02-14 13:23:03.840000', 'filename': '20220214T132303840.jpg'},
    {'convertedDate': '2022-02-14 13:23:07.860000', 'filename': '20220214T132307860.jpg'}
]

for i in range(len(a_list)):
    # 核心取值写法:通过索引取当前字典,再取filename对应的文件名
    current_filename = a_list[i]['filename']
    img = load_img(current_filename, target_size=(64, 64))
    final_list.append(img)

注意事项

  • 不要依赖「字典第二个键」的位置取值:Python 3.7之前的字典不保证键的插入顺序,直接用明确的filename键名取值兼容性更强,不会因为字典结构变动取错值。
  • 如果你的图片不在当前运行脚本的同级目录,需要在文件名前拼接对应的文件路径,否则load_img会报文件不存在错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 10:21:18