Python 中错误 AttributeError: 'Dict' Object Has No Attribute 'Append'
dict是一种使用hash map的数据结构,区别于list。 它没有 append()
函数,而列表数据结构有 append()
函数。
Python中错误AttributeError: 'Dict' Object Has No Attribute 'Append'
字典可以在其中包含一个列表。 我们不能直接追加字典,但如果字典中有一个列表,我们可以很容易地追加它。
例如,
>>> dict = {}
>>> dict["numbers"]=[1,2,3]
>>> dict["numbers"]
[1, 2, 3]
>>> dict["numbers"].append(4)
>>> dict["numbers"]
[1, 2, 3, 4]
在这里,数字键有一个列表作为值。 我们可以追加它,但假设我们想追加字典。
它将显示以下错误:
>>> dict = {}
>>> dict["numbers"]=[1,2,3]
>>> dict.append(12)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'
处理 Python中 AttributeError: 'dict' object has no attribute 'append' 错误
该值可以是任何类型:元组、列表、字符串,甚至是另一个字典。 为防止此错误,我们可以检查字典中特定键的值类型。
为此,我们需要评估键是否存在于字典中。
让我们看下面的例子:
dict = {}
dict["nums"] = [1,2,3]
dict["tuple"] = (1,2,3)
dict["name"] = "Alex"
if dict.get("name", False):
if type(dict["name"]) is list:
dict["name"].append("Another Name")
else:
print("The data type is not a list")
else:
print("This key isn't valid")
输出:
The data type is not a list
它可能会像前一个一样给我们错误,但我们正在评估字典的键。 然后我们检查该值是否为列表。
之后,我们将附加列表。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。