首页 > 解决方案 > 为什么我会收到此错误 AttributeError: 'str' object has no attribute 'get' where get function is on a dictionary?

问题描述

我有一本字典:

fruits = {
"apple": ["red", "juicy"]
}

fruits字典在许多函数中传递和返回。我不知道为什么,但在这行代码中我得到一个AttributeError.

def get_dict(dict):
    dictionary = dict
    appels_attributes = dictionary.get("apple")
    return apples_attributes

print(get_dict(fruits))

有什么问题还是我错过了什么?

标签: pythondictionary

解决方案


首先你需要检查你的语法。在您的代码中:

def get_dict(dict):
    dictionary = dict
    appels_attributes = dictionary.get("apple")
    # appels and apples are not equal.
    return apples_attributes

我认为你犯了一些拼写错误。第 3
行:苹果 第 4 行:苹果

所以只定义了一个变量。那是“appels_attributes”,而您返回了未定义的“apples.attributes”。这就是您收到属性错误的原因。

并且不要使用任何保留的语法,例如“dict”,这些是由 python 预定义的。


推荐阅读