On Wed, 10 Jun 2020 at 23:02, Peter Otten <__pete...@web.de> wrote: > > However later when I actually use it, accessing a key that is not > > present, should raise KeyError. > > > > Is that somehow possible? > > It never occured to me to try that, but: > > >>> from collections import defaultdict > >>> d = defaultdict(list) > >>> d["x"] > [] > >>> d.default_factory = None > >>> d["y"] > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > KeyError: 'y'
An alternative approach to this would be to use a regular dict from the start... d.setdefault("x", []).append("stuff") -- Matt Wheeler http://funkyh.at -- https://mail.python.org/mailman/listinfo/python-list