DEV Community

qing
qing

Posted on • Edited on

Quick Tip: `dict.setdefault()` eliminates boilerplate key checks

Quick Tip: dict.setdefault() eliminates boilerplate key checks

When working with dictionaries in Python, it's common to encounter situations where you need to check if a key exists before attempting to access or modify its value. Traditionally, this has been done using an if statement to check if the key is present in the dictionary. However, this approach can lead to boilerplate code and make your scripts less readable.

Before: Manual key check

d = {'a': 1, 'b': 2}

if 'c' not in d:
    d['c'] = []
d['c'].append(3)
Enter fullscreen mode Exit fullscreen mode

As you can see, this approach requires an explicit check for the key's


Follow me on Dev.to for daily Python tips and quick guides!


🔗 Recommended Resources

Note: Some links are affiliate links. Using them supports this blog at no extra cost to you.


If you found this useful, you might like Python Automation Scripts Pack (10 Ready-to-Use Tools) — a practical resource that takes things a step further. At $14.99 it's a solid investment for your toolkit.


喜欢这篇文章?关注获取更多Python自动化内容!

Top comments (0)