AttributeError: 'list' object has no attribute 'get' 主要发生在你试图调用get()方法时发生。该属性get()方法存在于 dictionary 中,必须在 dictionary 数据类型上调用。
在本教程中,我们将了解什么是 AttributeError: 'list' object has no attribute 'get' 以及如何通过实例解决这个错误。
什么是 AttributeError: 'list' object has no attribute 'get'?
如果我们在 list 数据类型上调用get()方法,Python 将引发AttributeError: 'list' 对象没有属性 'get'。如果你有一个返回list而不是 dictionary 的方法,这个错误也可能发生。
让我们举一个简单的例子来重现这个错误。
# Method return list of dict
def fetch_data():
cars = [
{'name': 'Audi', 'price': 45000},
{'name': 'Ferrari', 'price': 450000},
{'name': 'BMW', 'price': 55000},
]
return cars
data = fetch_data()
print(data.get("name"))
输出
AttributeError: 'list' object has no attribute 'get'
在上面的例子中,我们有一个方法 fetch_data()返回一个 list的 dictionary 对象 ,而不是一个dictionary。
由于我们在列表类型上直接调用get()方法,我们得到AttributeError。
我们也可以检查变量类型是否使用了type()方法,并且使用dir()方法,我们还可以打印一个给定对象的所有属性的列表。
# Method return list of dict
def fetch_data():
cars = [
{'name': 'Audi', 'price': 45000},
{'name': 'Ferrari', 'price': 450000},
{'name': 'BMW', 'price': 55000},
]
return cars
data = fetch_data()
print("The type of the object is ", type(data))
print("List of valid attributes in this object is ", dir(data))
输出
The type of the object is <class 'list'>
List of valid attributes in this object is ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
如何解决 AttributeError: 'list' object has no attribute 'get'?
让我们看看如何解决这个错误。
解决方案 1 - 对有效的字典调用 get() 方法
我们可以通过调用 get()方法来解决这个问题,在有效的字典对象上而不是在列表 类型上。
因为数据里面有一个有效的字典对象。 list中有一个有效的字典对象,我们可以循环浏览这个列表,并在字典元素上使用 get()方法在 dictionary 元素上使用。
该 dict.get()方法返回给定键的值。如果键不存在,该方法不会抛出 KeyError。 get()方法不会在键不存在的情况下抛出KeyError;相反,我们会得到 None值或我们在方法中传递的默认值。 get()方法中传递的值或默认值。
# Method return list of dict
def fetch_data():
cars = [
{'name': 'Audi', 'price': 45000},
{'name': 'Ferrari', 'price': 450000},
{'name': 'BMW', 'price': 55000},
]
return cars
data = fetch_data()
for item in data:
print(item.get("name"))
输出
Audi
Ferrari
BMW
我们还可以使用 generator expression, filter函数来获取特定的字典元素,或者直接使用 index的列表。让我们用例子来看看这些方法中的每一个。
# Method return list instead of dict
def fetch_data():
cars = [
{'name': 'Audi', 'price': 45000},
{'name': 'Ferrari', 'price': 450000},
{'name': 'BMW', 'price': 55000},
]
return cars
data = fetch_data()
# Generator expression to get specific element
car_obj = next(
(x for x in data if x['name'] == 'BMW'),
{}
)
print(car_obj)
print("Car Name is ", car_obj.get("name"))
print("Car Price is ", car_obj.get("price"))
# Directly access the dictionary using the index of list
print("The car name in index 0 is ", data[0].get("name"))
输出
{'name': 'BMW', 'price': 55000}
Car Name is BMW
Car Price is 55000
The car name in index 0 is Audi
解决方案 2 - 使用 type 检查对象是否是 dictionary 类型的
另一种方法是检查对象是否是 dictionary 类型;我们可以用 type()方法。这样,我们可以在调用方法之前检查对象的数据类型是否正确。 get()方法。
# Method return list of dict
def fetch_data():
cars = [
{'name': 'Audi', 'price': 45000},
{'name': 'Ferrari', 'price': 450000},
{'name': 'BMW', 'price': 55000},
]
return cars
# assigns the list of dict
data = fetch_data()
if (type(data) == dict):
print(data.get("name"))
else:
print("The object is not dictionary and it is of type ", type(data))
# assign the index 0 dict
my_car =data[0]
if (type(my_car) == dict):
print(my_car.get("name"))
else:
print("The object is not dictionary and it is of type ", type(my_car))
输出
The object is not dictionary and it is of type <class 'list'>
Audi
解决方案3--使用hasattr检查该对象是否有get属性
在调用 get()方法之前,我们还可以检查对象是否具有某种属性。即使我们调用一个返回不同数据的外部API,使用 hasattr()方法,我们可以检查该对象是否有一个给定名称的属性。
# Method return list of dict
def fetch_data():
cars = [
{'name': 'Audi', 'price': 45000},
{'name': 'Ferrari', 'price': 450000},
{'name': 'BMW', 'price': 55000},
]
return cars
# assigns the list of dict
data = fetch_data()
if (hasattr(data, 'get')):
print(data.get("name"))
else:
print("The object does not have get attribute")
# assign the index 0 dict
my_car = data[0]
if (hasattr(my_car, 'get')):
print(my_car.get("name"))
else:
print("The object does not have get attribute")
输出
The object does not have get attribute
Audi
总结
当你试图在 list 数据类型上直接调用方法时,会出现AttributeError: 'list' object has no attribute 'get' 。get()方法时,会发生 AttributeError: 'list ' object has no attribute 'get' 。如果调用方法返回一个list 而不是dictionary 对象,也会发生这个错误。
我们可以通过以下方法解决这个错误 get()方法,而不是直接在 list 上调用 get() 方法来解决这个问题。我们可以使用 type()方法来检查对象是否属于 dictionary 类型,同时,我们可以在执行 get 操作之前,用 hasattr()在执行 get 操作之前检查对象是否有有效的 get 属性。