.get()

MamtaWardhani's avatar
Published May 23, 2022Updated May 11, 2025
Contribute to Docs

The .get() method is a built-in dictionary method in Python that retrieves the value for a specified key from a dictionary. This method provides a safe way to access dictionary values without raising a KeyError when the key doesn’t exist. Instead of throwing an exception, the .get() method returns None (by default) or a user-specified default value when the requested key is not found.

The .get() method is commonly used in data processing, web development, and configuration management, where safe access to dictionary values is needed without interrupting program flow. It is beneficial when dealing with API responses, user inputs, or any scenario where the presence of a key is uncertain.

Syntax

dictionary.get(key, value)

Parameters:

  • key: The key to search for in the dictionary.
  • value (optional): The value to return if the key is not found in the dictionary. If not specified, the default value is None.

Return value:

  • The .get() method returns the value for the specified key if the key exists in the dictionary. If the key does not exist, it returns the specified default value or None if no default value is provided.

Example 1: Basic Dictionary Access using .get()

This example demonstrates how to use the .get() method to retrieve values from a dictionary and gracefully handle missing keys.

# Creating a dictionary of student scores
student_scores = {
"Alice": 92,
"Bob": 85,
"Charlie": 78
}
# Retrieving values with the get() method
alice_score = student_scores.get("Alice")
dave_score = student_scores.get("Dave") # Key doesn't exist
eve_score = student_scores.get("Eve", 0) # Key doesn't exist, using default value
# Printing the results
print(f"Alice's score: {alice_score}") # Will print the value
print(f"Dave's score: {dave_score}") # Will print None
print(f"Eve's score: {eve_score}") # Will print 0 (default value)

The output generated by this code will be:

Alice's score: 92
Dave's score: None
Eve's score: 0

In this example, retrieving values from a dictionary of student scores is shown. Accessing “Alice” yields her actual score. For “Dave”, since the key doesn’t exist and no default value is provided, .get() returns None. For “Eve”, specifying a default value of 0 results in that value being returned because the key doesn’t exist.

Example 2: Preventing KeyErrors in Data Processing

This example shows how .get() can be used to safely process data from an API response or user input without exception handling:

# Simulating a product catalog with inconsistent data structure
products = [
{"id": 1, "name": "Laptop", "price": 999.99, "stock": 45},
{"id": 2, "name": "Mouse", "price": 24.99}, # Missing 'stock' key
{"id": 3, "name": "Keyboard", "stock": 32}, # Missing 'price' key
{"id": 4, "name": "Monitor", "price": 149.99, "stock": 0}
]
# Processing products safely with get()
def calculate_inventory_value(product_list):
total_value = 0
for product in product_list:
# Using get() to safely retrieve price and stock with defaults
price = product.get("price", 0)
stock = product.get("stock", 0)
# Calculate item value and add to total
item_value = price * stock
total_value += item_value
print(f"Product: {product.get('name', 'Unknown')}, Value: ${item_value:.2f}")
return total_value
# Calculate and display total inventory value
total = calculate_inventory_value(products)
print(f"\nTotal inventory value: ${total:.2f}")

The output produced by this code will be:

Product: Laptop, Value: $44999.55
Product: Mouse, Value: $0.00
Product: Keyboard, Value: $0.00
Product: Monitor, Value: $0.00
Total inventory value: $44999.55

This example processes a list of product dictionaries with inconsistent data. By using .get() with default values, the inventory value can be safely calculated even when some keys are missing, avoiding KeyError exceptions.

Codebyte Example: Nested Dictionary Navigation

This example demonstrates how to use .get() for safely navigating nested dictionaries, a common scenario when working with JSON data:

Code
Output
Loading...

This function allows for safely accessing values in nested dictionaries. It returns a specified default when no key in the given path exists.

Frequently Asked Questions

1. What is the difference between using .get() and direct dictionary access with square brackets?

Using dictionary[key] will raise a KeyError exception if the key doesn’t exist, while dictionary.get(key) will return None or a specified default value. Use .get() to handle missing keys gracefully without exception.

2. Can I use .get() with non-string keys?

Yes, .get() works with any valid dictionary key type in Python, including numbers, tuples, and even custom objects that implement the __hash__ and __eq__ methods.

3. Does .get() create the key in the dictionary if it doesn’t exist?

No, .get() only retrieves values and doesn’t modify the dictionary. If you want to add a key-value pair when the key doesn’t exist, use the .setdefault() method instead.

4. What are the usages of dictionary copy(), get(), items(), and keys() methods?

  • .copy(): Creates a shallow copy of the dictionary, which means it creates a new dictionary with the duplicate keys and values but doesn’t copy nested objects.
  • .get(): Safely retrieves the value for a specified key, returning a default value if the key doesn’t exist.
  • .items(): Returns a view object containing key-value pairs as tuples, useful for iterating through all elements in a dictionary.
  • .keys(): Returns a view object containing all the keys in the dictionary, which can be used to iterate through the keys or convert to a list.

5. How does .get() compare to using a try-except block with dictionary access?

Both approaches handle missing keys, but they have different use cases:

  • Use .get() when a missing key is an expected scenario and you want a default value
  • Use try-except when a missing key represents an error condition or when you need to perform additional error handling

All contributors

Contribute to Docs

Learn Python on Codecademy