ky = ['a','b','c']
val = 15
dict_1 = dict.fromkeys(ky,[])
dict_1['a'].append(val)
dict_2 = {'a':[],'b':[],'c':[]}
dict_2['a'].append(val)
print(dict_1)
print(dict_2)
>Solution :
Please correct me if I’m wrong, but given your post, I’m presuming your question is why dict_1 has the same value (15) for all its keys a, b, and c as the end result, right?
If so, I agree that this is unintuitive behavior at a first glance, but what is happening is that by passing [] (an empty list) as the second optional argument for the fromkeys method, you’re populating dict_1 dictionary with references to the same single empty list, hence, when you append val to the key a, all other keys are updated with the same value as well (you passed the empty list as reference. see difference between passing by reference vs passing by value ).
As you noticed yourself, there are other ways to initialize a dictionary of empty lists in Python (as you did "manually" with dict_2).
In case you’re interested in another "less manual" way to initialize a dictionary of empty lists in Python, you could use a list comprehension to do so, as in the following example:
dict_3 = {k : [] for k in ky}
That would initialize dict_3 with empty lists (passed by value), thus, keys b and c would be unaffected when you append val to the key a.
I hope that helps to clarify your example. Kind regards.