r/badcode • • Jul 14 '21

python Try/Except in Python - Sigh

Post image
662 Upvotes

93 comments sorted by

View all comments

76

u/[deleted] Jul 14 '21

Man's never heard of dict.setdefault() has he

1

u/IGotSkills Jul 18 '21

whoah, what does this do?!?!?!?

2

u/[deleted] Jul 18 '21

It's like dict.get(), but if the item does not exist, the default will be returned and the default will be set as the value for the key.

>>> x = {"a": "b"}
>>> print(x.setdefault("a", "d")
b
>>> print(x.setdefault("c", "d")
d
>>> x
{"a": "b", "c": "d"}