0

Is it possible (in Python 3.6+) to have or implement dict comprehensions on a dict subclass, with the result being an instance of that subclass instead of a normal dict? Something like CustomDict{k: v for k, v in list_of_tuples}?

Is there any way at all to customize list/dict comprehensions?

gmolau
  • 2,815
  • 1
  • 22
  • 45

1 Answers1

1

Your subclass can consume an iterable of 2-tuples:

CustomDict((k, v) for k, v in list_of_tuples)

You can't use the language construct style {...} on your subclass, unless of course, you want to tweak some Python internals.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Thanks, that would work. I had never thought about a comprehension and its enclosing brackets as syntactically separate things, but it looks like [they are](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries). – gmolau Jan 26 '18 at 00:37