Python 中 AttributeError: ‘list’ object has no attribute ‘items’ 错误
当我们在列表而不是字典上调用 items()
方法时,会出现 Python“AttributeError: ‘list’ object has no attribute ‘items’ ”。 要解决错误,需要在字典上调用 items()
,例如 通过访问特定索引处的列表或遍历列表。
下面是一个产生上述错误的示例
my_list = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Alice'},
]
# ⛔️ AttributeError: 'list' object has no attribute 'items'
print(my_list.items())
我们创建了一个包含 3 个字典的列表,并尝试在导致错误的列表上调用 items()
方法,因为 items()
是一个字典方法。
解决该错误的一种方法是访问特定索引处的列表元素。
my_list = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Alice'},
]
result = list(my_list[0].items())
print(result) # 👉️ [('id', 1), ('name', 'Alice')]
如果需要对列表中的所有字典调用 items()
方法,请使用 for 循环。
my_list = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Carl'},
]
for person in my_list:
print(person.items())
dict.items
方法返回字典项((键,值)对)的新视图。
my_dict = {'id': 1, 'name': 'Alice'}
print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'Alice')])
字典是包含在大括号中的键值对的集合,而列表是一系列以逗号分隔的项目。
如果我们需要在列表中查找字典,请使用生成器表达式。
my_list = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Carl'},
]
result = next(
(item for item in my_list if item['name'] == 'Bob'),
{}
)
print(result) # 👉️ {'id': 2, 'name': 'Bob'}
print(result.get('name')) # 👉️ "Bob"
print(result.get('id')) # 👉️ 2
print(result.items()) # 👉️ dict_items([('id', 2), ('name', 'Bob')])
示例中的生成器表达式查找名称键值为 Bob 的字典并返回该字典。
我们使用一个空字典作为回退,所以如果列表中的字典有一个值为 Bob 的名称键,生成器表达式将返回一个空字典。
如果我们需要在列表中查找所有符合条件的字典,请使用 filter()
函数
my_list = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Alice'},
]
new_list = list(
filter(lambda person: person.get('name') == 'Alice', my_list)
)
# 👇️ [{'id': 1, 'name': 'Alice'}, {'id': 3, 'name': 'Alice'}]
print(new_list)
当我们尝试在列表而不是字典上调用 items()
方法时,会出现“AttributeError: ‘list’ object has no attribute ‘items’ ”。 我们可以使用 dir()
函数查看对象具有的所有属性。
my_list = ['a', 'b', 'c']
# 👉️ [... 'append', 'clear', 'copy', 'count', 'extend', 'index',
# 'insert', 'pop', 'remove', 'reverse', 'sort' ...]
print(dir(my_list))
如果将一个类传递给 dir()
函数,它会返回该类属性的名称列表,并递归地返回其基类的属性。
如果我们尝试访问不在此列表中的任何属性,将收到“AttributeError: list object has no attribute”错误。
由于 items()
不是列表实现的方法,所以导致错误。
总结
当我们在列表而不是字典上调用 items()
方法时,会出现 Python“AttributeError: ‘list’ object has no attribute ‘items’”。 要解决错误,请在字典上调用 items()
,例如 通过访问特定索引处的列表或遍历列表。