将空列表添加到字典值

时间:2020-08-24 12:13:40

标签: python list dictionary

当我为此编码时:

for key, value in d.items():
    d[key].append([])

它说,

AttributeError: 'int' object has no attribute 'append'

我不明白此错误消息。这里的int对象是什么,以及如何对将空列表添加到字典值进行编码?

1 个答案:

答案 0 :(得分:0)

值的类型(d[key]是整数,.append()方法不适用于整数。

如果“问题”为空,则将空白列表作为值添加到字典中,如果值(d[key])为空,则

d = {'a':2, 'b': None, 'c':3}
for key, value in d.items():
    if not d[key]:
       d[key] = []
print(d)

输出:{'a': 2, 'b': [], 'c': 3}