← Back to Blog

How to Ask a Dict for What You Need

The problem...

You have a dict. Data is in there — names, scores, settings, whatever it is.

Now you need to get it out.

There's more than one way to do it. And the wrong choice at the wrong moment raises an error.

The idea!

Python gives you two ways to look up a value in a dict.

One is direct. One is safe. You need to know both — and when to use which.

Square bracket lookup

The most direct way: the key in square brackets.

soldier = {"name": "Raven", "score": 85, "active": True}
print(soldier["name"])
print(soldier["score"])

Output:

Raven
85

Fast, clean, readable. Use this when you're certain the key exists.

If the key doesn't exist — KeyError. No second chances.

print(soldier["rank"])    # KeyError: 'rank'

The safe way — get()

get() looks up a key and returns None if it doesn't exist — no error.

soldier = {"name": "Raven", "score": 85}
print(soldier.get("name"))
print(soldier.get("rank"))

Output:

Raven
None

You can also set a default value to return instead of None:

print(soldier.get("rank", "unassigned"))

Output → unassigned

The dict is not changed. The default is just what gets returned if the key is missing.

Checking before looking up

If you want to use square brackets but aren't sure the key exists, check first:

soldier = {"name": "Raven", "score": 85}

if "rank" in soldier:
    print(soldier["rank"])
else:
    print("No rank assigned.")

Output → No rank assigned.

Getting all keys, all values, all pairs

Three methods give you a view of the whole dict:

soldier = {"name": "Raven", "score": 85, "active": True}

print(soldier.keys())
print(soldier.values())
print(soldier.items())

Output:

dict_keys(['name', 'score', 'active'])
dict_values(['Raven', 85, True])
dict_items([('name', 'Raven'), ('score', 85), ('active', True)])

These aren't lists — but you can loop over them, which is what you'll do most of the time.

You'll see them in action in the iteration lesson.

What's really happening

Square brackets go directly to the key. If it's not there, Python raises an error immediately.

get() does the same lookup but catches the missing key silently and returns a fallback instead.

Neither method modifies the dict.

Heads up!

  • Square brackets raise KeyError if the key is missing — use when you're certain
  • get() returns None by default — use when the key might not exist
  • get(key, default) returns your default instead of None
  • keys(), values(), items() return views — not lists
  • Key lookup is case-sensitive — "Name" and "name" are different keys

The mindset shift

Stop thinking: "I'll just use square brackets and hope the key is there."

Start thinking: "Do I know this key exists? Square brackets. Not sure? get()."

What you should understand now

  • dict["key"] returns the value — raises KeyError if missing
  • dict.get("key") returns the value — returns None if missing
  • dict.get("key", default) returns the default if the key is missing
  • Use in to check if a key exists before looking it up
  • keys(), values(), items() give you views of the whole dict
[ login to bookmark ] // copied! 18 views · 2 min
// resources
Code Example dict_reading.py
← prev From Empty to Full: How to Create Dicts in Python next → How to Modify a Dict
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.