DEV Community

qing
qing

Posted on

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

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 assigning a value to it. This can lead to boilerplate code that clutters your scripts. Let's take a look at a typical example:

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

In this example, we're checking if the key 'c' exists in the dictionary d. If it doesn't, we create a new key with an empty list


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


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*

Top comments (0)