Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Dictionary Value Access: Bracket vs. get()

Learn how to access Python dictionary values with bracket syntax and .get(), and when to choose each approach.

~4 min readPython
#Python dictionaries#dict.get()#KeyError handling#Python data structures
Illustration of a Python dictionary with two access paths: bracket notation raising KeyError and .get() returning a default value.

When you need to read a value from a Python dictionary, the language gives you two standard tools: bracket access (d["key"]) and the .get() method (d.get("key")). Both return the value associated with a key, but they behave very differently when the key does not exist. Understanding that difference matters in real code, because the wrong choice produces either a crash or a silently missing value.

Bracket Access Raises KeyError for Missing Keys

python
config = {"host": "localhost", "port": 5432} host = config["host"] # "localhost" timeout = config["timeout"] # KeyError: 'timeout'

The bracket operator performs a direct lookup in the dictionary's internal hash table. When the key is present, you get the value immediately. When it is absent, Python raises KeyError. This behavior is intentional: bracket access is the strict form of lookup, and it treats a missing key as a programming error rather than a normal condition.

Use bracket access when the key is required for the code to proceed correctly. If the dictionary is missing that key, the KeyError surfaces the problem at the point of access, which is usually where you want the failure to appear. Silently substituting a default in that situation could hide a configuration bug or a malformed data structure.

The .get() Method Returns a Default Instead of Raising

python
config = {"host": "localhost", "port": 5432} timeout = config.get("timeout") # None timeout = config.get("timeout", 30) # 30

The .get() method never raises KeyError. With one argument, it returns None when the key is absent. With a second argument, it returns that value instead. This makes .get() the lenient form of lookup, suitable for keys that are genuinely optional.

The second argument is evaluated eagerly, so config.get("timeout", expensive_default()) calls expensive_default() even when the key exists. If the default is costly to construct, compute it lazily or use a sentinel:

python
_MISSING = object() value = config.get("key", _MISSING) if value is _MISSING: value = build_default()

Choosing Between Bracket Access and .get()

The decision is not about style; it is about what a missing key means in your specific code path.

Use bracket access when a missing key indicates a bug. Configuration files, parsed records, and internal data structures often have required fields. If one is missing, you want the KeyError to propagate so the failure is visible.

Use .get() when a key is optional or when the data comes from an external source with an unknown schema. A user-supplied JSON payload, for example, may or may not contain a particular field, and treating that as an error would break valid inputs.

Another option exists when you need to distinguish a missing key from a key whose value is None. The in operator checks membership directly:

python
if "timeout" in config: timeout = config["timeout"] else: timeout = 30

This pattern is more verbose than .get(), but it preserves the distinction between an absent key and a key whose value is None. That distinction matters when None is a meaningful value in your domain.

Accessing Values in Nested Dictionaries

Nested dictionaries are common in JSON-derived data. Accessing a value at depth requires handling missing keys at every level.

python
user = {"profile": {"name": "Ada", "settings": {"theme": "dark"}}} theme = user["profile"]["settings"]["theme"] # "dark"

Bracket access at each level raises KeyError if any intermediate key is missing. Chained .get() calls avoid that, but they become unwieldy:

python
theme = user.get("profile", {}).get("settings", {}).get("theme")

This returns None for any missing level, but the empty-dictionary defaults are a code smell. If you find yourself writing this pattern often, consider flattening the structure or using a dedicated data class instead of nested dictionaries. Deep nesting makes every access path a potential failure point, and the defensive code obscures the actual data shape.

Runtime Cost and Exception Handling

Bracket access can be marginally faster than .get() because it avoids a method call and goes straight to the underlying lookup operation. In practice, the difference is usually small enough that it rarely matters outside tight loops processing many records. The more significant cost is in exception handling: catching a KeyError can be much more expensive than checking membership with in or using .get() with a default when misses are common.

python
# Avoid this pattern in hot paths try: value = config["timeout"] except KeyError: value = 30

The try/except version is correct, but it can be slower than config.get("timeout", 30) when misses are common, because exception handling unwinds the stack. Prefer .get() for simple defaults. Use bracket access without try/except when a missing key should fail loudly, and use the try/except form when you need custom handling beyond a simple default or when misses are rare enough that the cost does not matter.

Distinguishing Missing Keys from None Values

A common bug appears when a key exists but its value is None. .get() returns None for both cases, so you cannot tell them apart:

python
data = {"retries": None} data.get("retries") # None data.get("retries", 3) # None, not 3

The default argument only applies when the key is absent, not when the value is None. If your data can contain explicit None values, test membership explicitly instead of relying on .get()'s default:

python
retries = data["retries"] if "retries" in data else 3

This subtlety causes real production bugs when optional fields are serialized as null in JSON and then read back with .get(). The default silently does not apply, and downstream logic receives None instead of the intended fallback.

A Practical Rule for Dictionary Value Access

The rule that holds up across most codebases is simple: use bracket access for required keys and .get() for optional keys. When you need to know whether a key exists at all, use in. When the value itself can be None, avoid .get() with a default and check membership explicitly.

For nested structures, prefer flat, typed representations when the nesting depth grows beyond two levels. The access syntax is only part of the problem; the real risk is the proliferation of defensive .get() chains that hide data-shape errors until much later in the program.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.