Reading values from a dictionary looks trivial in Python.
But depending on how you do it, you may introduce silent bugs, unexpected KeyErrors, or logic errors that only appear in production.
In this short tutorial, we’ll compare:
Direct indexing
dict.get()
dict.setdefault()
And see when each one is correct — and when it’s dangerous.
1. Direct indexing
config = {"timeout": 10}
timeout = config["timeout"] # OK
retries = config["retries"] # KeyError
When to use it
Use direct indexing only when the key must exist.
2. dict.get(): Safe Reads
timeout = config.get("timeout", 5)
retries = config.get("retries", 3)
When to use it
- To avoid KeyErrors, when key doesn't exist
- When key doesn't exist, want to return a default value
3. dict.setdefault(): Read + Initialize
counts = {}
counts.setdefault("apple", 0)
counts["apple"] += 1
When to use it
Whe a key doesn't exist, you want to create it.
Final rule of thumb
Use d[key] when the key must exist
Use get() when missing keys are normal
Use setdefault() only when initializing structures
2Posts
0Comments
5Followers
6Connections
Hi there! I'm a Python Passionista with 8 years of experience in the field. I'm also a fan of Linux and the free software ideas. I usually find myself configuring my desktop(currently Arch+Hyprland) or Neovim :)
✨ Build your own developer journey
Track progress. Share learning. Stay consistent.