Three Ways to Read from a Dict in Python

posted 1 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

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

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

10 Proven Ways to Cut Your AWS Bill

rogo032 - Jan 16
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

7 comments
3 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!