What is the output of the following code involving __missing__? class DefaultList(dict): def __missing__(self, key): self[key] = [] return self[key] d = DefaultList() d[‘a’].append(1) d[‘a’].append(2) d[‘b’].append(3) print(d)

Python Professional Hard

Python Professional — Hard

What is the output of the following code involving __missing__? class DefaultList(dict): def __missing__(self, key): self[key] = [] return self[key] d = DefaultList() d[‘a’].append(1) d[‘a’].append(2) d[‘b’].append(3) print(d)

Key points

  • __missing__ method creates a default value for missing keys
  • Appending values to existing keys modifies the dictionary
  • The DefaultList class ensures keys always have a list as a value

Ready to go further?

Related questions