Safely Handling Dictionaries in Python with setdefault()
Safely Handling Dictionaries in Python with setdefault() ๐งฉ
Python’s setdefault() method lets you access a dictionary value,
or assign a default if the key is missing — all in one line.
It’s a great alternative when defaultdict isn’t available or needed.
✅ Basic usage
# Basic use of setdefault()
data = {}
data.setdefault('name', 'Unknown')
print(data) # {'name': 'Unknown'}
✅ Will not overwrite existing keys
# If key exists, do not override
data = {'name': 'Alice'}
data.setdefault('name', 'Bob')
print(data) # {'name': 'Alice'}
✅ Safely count values
# Count occurrences without initializing
counter = {}
for item in ['apple', 'banana', 'apple']:
counter.setdefault(item, 0)
counter[item] += 1
print(counter) # {'apple': 2, 'banana': 1}
✅ Like defaultdict, without importing anything
# Similar to defaultdict pattern
words = ['cat', 'dog', 'cat']
group = {}
for word in words:
group.setdefault(word, []).append('✓')
print(group) # {'cat': ['✓', '✓'], 'dog': ['✓']}
setdefault() keeps your code clean and safe from KeyErrors.
It’s ideal for counting, grouping, or initializing nested values on the fly.
When in doubt, set it by default. Clean, safe, and Pythonic. ๐
Icons by Flaticon
Comments
Post a Comment