Creating a dict of lists using different methods
d1 = {'foo':[],'bar':[]}
d2 = dict.fromkeys(['foo','bar'],[])
yield two identical dicts.
print(d1==d2,d1,d2)
True {'foo': [], 'bar': []} {'foo': [], 'bar': []}
However, appending values to the lists
d1['foo'].append('a')
d2['foo'].append('a')
d1['foo'].append(2)
d2['foo'].append(2)
yields two different dicts. Why does the initialization method of a dict affect the list append behaviour?
print(d1==d2,d1,d2)
False {'foo': ['a', 2], 'bar': []} {'foo': ['a', 2], 'bar': ['a', 2]}
After fromkeys, python applies list append statements to all other keys too.