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

Python中如何将列表转为字典以解决'list has no attribute items'错误?

问题解决方法

错误原因

报错AttributeError: 'list' object has no attribute 'items'的核心问题有两个:

  1. 代码误用Python内置类型list调用items()方法,逻辑完全错误——你需要遍历的是前面定义的table变量,而非内置的list类型。
  2. 可能存在隐藏问题:通过pickle.load读取的table实际是列表,而非预期的字典,导致后续遍历逻辑不匹配。

针对性修复方案

方案1:修正变量名(预期pickle存储的是字典)

如果原代码设计是table_file里存储字典,只需把错误的list.items()改成table.items():

def read_table(table_file):
    table = dict()
    with open(table_file, 'rb') as handle:
        while True:
            try:
                table = pickle.load(handle)
            except EOFError:
                break

    f_set=set()
    # 修正变量名,遍历table的键值对
    for k,v in table.items():
        for feature in v[DATA]:
            f_set.add(feature)
           
    return table , f_set

方案2:适配pickle存储的是列表的情况

如果table_file里实际存储的是列表,需根据列表元素结构调整遍历逻辑:

  • 若列表元素是(键, 值)形式的元组:
def read_table(table_file):
    table = dict()
    with open(table_file, 'rb') as handle:
        while True:
            try:
                table = pickle.load(handle)
            except EOFError:
                break

    f_set=set()
    # 直接遍历列表中的键值对元组
    for k,v in table:
        for feature in v[DATA]:
            f_set.add(feature)
           
    return table , f_set
  • 若列表元素是字典:
def read_table(table_file):
    table = dict()
    with open(table_file, 'rb') as handle:
        while True:
            try:
                table = pickle.load(handle)
            except EOFError:
                break

    f_set=set()
    # 先遍历列表中的每个字典,再遍历字典的键值对
    for item in table:
        for k,v in item.items():
            for feature in v[DATA]:
                f_set.add(feature)
           
    return table , f_set

额外注意点

代码中的DATA变量需确保已提前定义(比如作为字符串常量),否则会触发NameError。

内容的提问来源于stack exchange,提问作者mitra.P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:40:14