PythonObjectsBeginner

dict.get()

Safely reads a key from a dict, returning a default if missing.

Review the syntaxStudy the examplesOpen the coding app
value = data.get(key, default=None)

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Safely reads a key from a dict, returning a default if missing.

The dict.get() method provides a safe and efficient way to retrieve values from a Python dictionary without risking a KeyError. Internally, it performs a hash table lookup with an average time complexity of O(1). If the specified key exists in the dictionary, get() returns the corresponding value; otherwise, it returns a default value. By default, this value is None, but it can be customized via the second argument. This method is structurally superior to the 'if key in dict' pattern because it avoids redundant hashing and simplifies logic when handling missing configuration keys or sparse JSON data. An important edge case occurs when None is a valid value within the dictionary; in such cases, get() returning None can be ambiguous, requiring the use of a unique sentinel object or membership testing.

Quick reference

Syntax

value = data.get(key, default=None)

Inputs

Parameters

keyAny · Dictionary key to look up.
default (optional)Any · Value returned if key is missing.

See it in practice

Examples

1

Basic Safe Access

user_data = {"id": 101, "username": "dev_expert"}

# Key exists
user_id = user_data.get("id")

# Key missing, returns default
email = user_data.get("email", "no-email@example.com")

print(f"User: {user_id}, Email: {email}")
Output:
User: 101, Email: no-email@example.com

Demonstrates retrieving an existing key and providing a fallback string for a missing key.

2

Frequency Map Construction

words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}

for word in words:
    counts[word] = counts.get(word, 0) + 1

print(counts)
Output:
{'apple': 3, 'banana': 2, 'cherry': 1}

Uses get() to initialize counts at 0 for new keys, allowing for a single-line increment logic.

3

Handling Nested API Responses

response = {"metadata": {"status": "success"}, "payload": {}}

# Safely access nested data with default empty dict
user_settings = response.get("payload", {}).get("settings", "Default Settings")

print(user_settings)
Output:
Default Settings

Chaining get() with empty dictionary defaults to prevent errors when traversing multi-level data structures.

Debug faster

Common Errors

1

LogicError

Cause: Returning None for a missing key when None is also a valid value in the dictionary, leading to ambiguity.

Fix: Use a unique sentinel object or the 'in' operator to distinguish between a missing key and a value that is actually None.

d = {'active': None}
val = d.get('active') # Returns None. Is 'active' missing or set to None?
2

AttributeError

Cause: Assuming get() always returns a specific type (like a list) and immediately calling a method on it without a proper default.

Fix: Ensure the default argument matches the expected type (e.g., list, set) so subsequent method calls don't fail.

data = {}
data.get('items').append(1) # Raises AttributeError: 'NoneType' object has no attribute 'append'

Runtime support

Compatibility

Python 3.8+

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Safely reads a key from a dict, returning a default if missing.

key: Dictionary key to look up. default: Value returned if key is missing.

LogicError: Use a unique sentinel object or the 'in' operator to distinguish between a missing key and a value that is actually None. AttributeError: Ensure the default argument matches the expected type (e.g., list, set) so subsequent method calls don't fail.