
setdefault is an ugly dict method
Occasionally, I find myself solving simple Python quizzes while getting bored. Nothing special, but rather a way to keep myself in shape. Also, this is a good way to learn something new, as Python evolves, and I'd like to use new features wherever they are applicable. But this time, something went wrong. The quiz was quite simple: what is the return value for {i: i**2 for i in range(3)}.setdefault(2, 10) statement? I've never used setdefault() before, so it was a bit interesting, a tiny research and a mind exercise. I started to search for the resulting data I'm working on. The {i for i**2 for i in range(3)} results in the dict type, and this is an example of dict comprehension. Nothing and nothing complex. But what is setdefault() for? I am familiar with the .get(key, <default_value>) method I like to use. This beautiful approach allows us to get either the dict's value behind the key or the <default_value> one. But the question should be tricky, shouldn't it? So, I tried to guess the
Continue reading on Dev.to Python
Opens in a new tab



