Three Ways to Read from a Dict in Python

●2 ●8
calendar_today • schedule1 min read

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:

  1. Direct indexing

  2. dict.get()

  3. 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

1 Comment

1 vote
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Dashboard Operasional Armada Rental Mobil dengan Python + FastAPI

Masbadar - Mar 12

I Wrote a Script to Fix Audible's Unreadable PDF Filenames

snapsynapseverified - Apr 20

Cisco's Amy Chang: A Model's "Passport" Doesn't Tell You Where It Actually Came From

Tom Smithverified - Aug 27

Three Design-to-Code Rules Most Developers Ignore (That Will Make You a Better Engineer)

Joemetry - Sep 26

The Ancient Roman Calendar in Your Python Terminal: A Love Letter to Useless Code

nevmenandr - Oct 14
chevron_left
180 Points • 10 Badges
2Posts
0Comments
6Connections
Hi there! I'm a Python Passionista with 8 years of experience in the field. I'm also a fan of Linux ... Show more

Related Jobs

View all jobs →

Commenters (This Week)

4 comments
3 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!