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

Python调用my_func遇AttributeError等错误的排查与解决求助

解决AttributeError: 'int' object has no attribute 'items'问题

函数功能说明

这段代码的设计目标是:

  • 接收整数集合A,以及由字典组成的列表B(每个字典的键为整数,值是C类的实例)
  • 对列表中的每个字典,筛选出键存在于A中的键值对,生成新字典
  • 返回所有处理后的字典组成的列表

错误原因分析

  1. 直接传单个字典的问题:你传入的my_dic是单个字典,但函数定义里B的类型是List[Dict[int, C]](字典的列表)。遍历字典默认迭代它的键,所以for b in B会取到1、2这些整数,调用b.items()自然触发AttributeError。
  2. 转列表后的问题:如果直接用list(my_dic)得到的是键列表[1,2],遍历时b仍是整数;如果用list(my_dic.items())得到的是键值对元组列表,元组没有items()方法,同样报错。

解决方案

场景1:仅需处理单个字典

修改函数参数类型与逻辑,移除外层列表循环:

from typing import Set, Dict

# 补全C类定义(你代码中使用的C是一个自定义类)
class C:
    def __init__(self, X: float, Y: float, a: int):
        self.X = X
        self.Y = Y
        self.a = a

def my_func(A: Set[int], B: Dict[int, C]) -> Dict[int, C]:
    filtered_dict = {}
    for key, value in B.items():
        if key in A:
            filtered_dict[key] = value
    return filtered_dict

# 调用示例
A = {1, 2}
my_dic = {
    1: C(X=11.0, Y=34.25, a=1),
    2: C(X=51.76, Y=50.63, a=2),
    3: C(X=10.0, Y=20.0, a=3)  # 测试不在A中的键
}

result = my_func(A, my_dic)
print(result)
# 输出:{1: <__main__.C object at 0x...>, 2: <__main__.C object at 0x...>}

场景2:保留原函数逻辑(处理字典列表)

如果需要处理多个字典,调用时将单个字典包装成列表传入:

from typing import Set, Dict, List

class C:
    def __init__(self, X: float, Y: float, a: int):
        self.X = X
        self.Y = Y
        self.a = a

def my_func(A: Set[int], B: List[Dict[int, C]]) -> List[Dict[int, C]]:
    filtered_list = []
    for dic in B:
        filtered_dict = {}
        for key, value in dic.items():
            if key in A:
                filtered_dict[key] = value
        filtered_list.append(filtered_dict)
    return filtered_list

# 调用示例
A = {1, 2}
my_dic = {
    1: C(X=11.0, Y=34.25, a=1),
    2: C(X=51.76, Y=50.63, a=2),
    3: C(X=10.0, Y=20.0, a=3)
}

# 将字典放入列表中传入
result = my_func(A, [my_dic])
print(result)
# 输出:[{1: <__main__.C object at 0x...>, 2: <__main__.C object at 0x...>}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:05:28