首页 > 解决方案 > 为什么设置字典列表的键/值对填充所有字典?

问题描述

test = [{}]*5 # Creates [{}, {}, {}, {}, {}]
print(test[1]) # outputs "{}"

test[1]['asdf'] = 5

print(test)

这给出test[{'asdf': 5}, {'asdf': 5}, {'asdf': 5}, {'asdf': 5}, {'asdf': 5}]. 不知何故,列表中的所有字典都被设置为相同的值

但是如果我们以不同的方式初始化列表,这不会发生:

test2 = [{} for i in range(5)] # Also [{}, {}, {}, {}, {}]
test2[1]['asdf'] = 1

print(test2) 

test2现在等于[{}, {'asdf': 1}, {}, {}, {}],预期的结果。

标签: pythondictionary

解决方案


两者之间的区别在于,对于[{}]*5,Python 创建了一个 5 元素列表,其中包含方括号中给出的字典。IE。这是对同一词典的 5 种不同引用。

而另一种方法为列表中的每个元素创建一个新字典。

更详细的解释可以在重复的问题链接中找到


推荐阅读