$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · hard · #218

Which fix removes the bug?

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