What is the output of the following? “`python from collections import defaultdict d = defaultdict(list) d[‘a’].append(1) d[‘a’].append(2) d[‘b’].append(3) print(dict(d)) “`

Python Developer Hard

Python Developer — Hard

What is the output of the following? “`python from collections import defaultdict d = defaultdict(list) d[‘a’].append(1) d[‘a’].append(2) d[‘b’].append(3) print(dict(d)) “`

Key points

  • defaultdict allows appending values to keys without checking if the key exists
  • The output is a dictionary with keys 'a' and 'b' containing the appended values
  • Using defaultdict(list) ensures that the default value for each key is an empty list
  • The print statement converts the defaultdict to a regular dictionary

Ready to go further?

Related questions