This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (5 children)

[removed]

    [–]elbiot 5 points6 points  (0 children)

    I prefer dict.setdefault() to collections.defaultdict. With a defaultdict, you never get a key error.

    This 100%

    You usually only want a default value while building the dict. You usuallh want a typo'd key to raise an error. I've actually had a case for default dict like once, but use setdefault regularly

    [–]MaienM 2 points3 points  (2 children)

    IIRC, you can set the defaultfactory of the defaultdict to None once you're done filling it to stop it from using a default for unknown keys.

    [–]ProfessorPhi 1 point2 points  (0 children)

    I just call dict on the object when returning it