仅添加到字典中的一个列表

Adding to only one list in dictionary

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() 方法 returns 一个字典,其值指向完全相同的空列表,无论是哪个键。这使得该方法对于此应用程序的用处不如它本来可以发挥的作用(并且让不少用户感到困惑)。

来自docs

fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.

手动创建字典时,您将空列表的不同副本分配给值。

首选方法是使用 dictionary comprehension:

def stack_ov_test():
    my_set = set([1, 2, 1, 2, 3, 4, 3, 2, 3])
    my_dict = {k: [] for k in my_set}
    print(my_dict) # {1: [], 2: [], 3: [], 4: []}
    my_dict[1].append(0)
    print(my_dict)  # {1: [0], 2: [], 3: [], 4: []}

stack_ov_test()