Three Ways to Read from a Dict in Python

1 8
calendar_todayschedule1 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

180 Points9 Badges1 8
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.

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

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

Karol Modelskiverified - Mar 19

The Sovereign Vault — A Comprehensive Guide to Protocol-Driven AI

Ken W. Algerverified - Jun 4

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

Dharanidharan - Feb 9
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

7 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!