I am trying to initialize a Python dictionary of 12 keys, all set to empty lists to later populate with different values. Here is a simplified example of the issue
The naive solution returns the desired results but it's unpleasant to see a large body of code:
output = {
'a': [],
'b': [],
'c': []
}
output['a'].append(1)
output['b'].append(2)
output['c'].append(3)
print(output)
{'a': [1], 'b': [2], 'c': [3]}
However, when I attempt to create the dictionary via dict.fromkeys():
output = dict.fromkeys(('a', 'b', 'c'), [])
output['a'].append(1)
output['b'].append(2)
output['c'].append(3)
print(output)
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
Prior to appending, both methods return the same results - a dictionary of empty lists so I'm confused why the appending behavior is different. Please let me know if more information is needed