Which fix removes the bug?
keys = ['a', 'b'] groups = dict.fromkeys(keys, []) groups['a'].append(1) print(groups['b']) # expected []
- Pass
listinstead of[] - Use
groups.copy()before - Build it:
{k: [] for k in keys} - Call
dict(keys)instead
fromkeys reuses the one list object for every key, so all keys share it.
Play Problem Solving ▸