我有一个int,list的字典。我试图做的是循环“一些事情”。如果密钥存在于dict中,则将该项添加到lsit或者创建一个新列表并添加该项。 这是我的代码。
Line 27: AttributeError: 'int' object has no attribute 'append'
我的问题是双重的。
1.我收到以下错误,
Line 27 is the line marked with ***
var user = new Entities.User { Name = "John" };
context.Users.Add(user);
context.SaveChanges();
// Reference the user created in the Administrator table
context.Administradors.Add(new Entities.Administrator { UserId = user.Id });
context.SaveChanges();
我错过了什么导致错误。
答案 0 :(得分:2)
首先设置一个列表,然后使用值替换替换该列表
删除最后一行,它会破坏你的代码。 您可以使用 这一行替换了您的6 您还可以使用 和 对于缺失的键,会自动添加列表对象。这有一个缺点:后来的代码中有一个错误,它会意外地使用一个不存在的密钥,这会让你得到一个空列表,在调试错误时会让人感到困惑。else:
levels[curr_node.dist] = []
levels[curr_node.dist].append(curr_node.tree_node.val)
levels[curr_node.dist] = curr_node.tree_node.val
dict.setdefault()
method在缺少密钥时分配空列表,同时返回密钥的值,而不是使用if...else
:levels.setdefault(curr_node.dist, []).append(curr_node.tree_node.val)
if: ... else ...
行。collections.defaultdict()
object:from collections import defaultdict
levels = defaultdict(list)
levels[curr_node.dist].append(curr_node.tree_node.val)