【发布时间】:2021-04-26 01:42:51
【问题描述】:
def stack_ov_test():
my_set = set([1, 2, 1, 2, 3, 4, 3, 2, 3])
my_dictionary = dict.fromkeys(my_set, [])
my_dictionary[1].append(0)
print(my_dictionary) # {1: [0], 2: [0], 3: [0], 4: [0]}
我认为上面的代码几乎是不言自明的,这就是为什么这让我如此困扰。 我只是想从集合/列表中创建一个字典,然后逐渐将数据添加到每个键列表中。当引用我要附加的列表时,字典中的所有列表都被修改了。 有人可以解释一下我错过了什么吗? 非常感谢!
小编辑:
当我手动创建字典时,一切正常:
def stack_ov_test():
my_dictionary = {1: [], 2: [], 3: []}
my_dictionary[1].append(0)
print(my_dictionary) # {1: [0], 2: [], 3: []}
【问题讨论】:
-
fromkeys()对每个键使用相同的对象。它不会创建新对象 -
改用
collections.defaultdict(list) -
为什么不能使用
defaultdict?或使用字典理解
标签: python dictionary append fromkeys