How to turn a defaultdict into a normal dict.

Matt Wheeler m at funkyhat.org
Tue Jun 16 09:35:53 EDT 2020


On Wed, 10 Jun 2020 at 23:02, Peter Otten <__peter__ at 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


More information about the Python-list mailing list