Back to Python
2026-03-226 min read

get() (Python Programming)

Learn get() (Python Programming) step by step with clear examples and exercises.

Why This Matters

The get() method in Python is crucial when working with dictionaries as it allows you to access the value associated with a specific key without raising an error if the key is not found. This feature is essential for handling real-world scenarios such as user inputs or data fetched from APIs where keys may be missing or invalid.

Prerequisites

To fully understand this tutorial, you should have a basic understanding of Python programming and dictionaries. If you're new to these concepts, it is recommended that you review the following resources:

Core Concept

Definition and Syntax

The get() method in Python returns the value of a specified key from a dictionary, if it exists. If the key is not found, it can optionally return a default value instead of raising an error. The syntax for using the get() method is as follows:

dict_name.get(key[, default])

In this syntax:

  • dict_name is the name of your dictionary.
  • key is the key you are trying to access.
  • default (optional) is the value to be returned if the specified key is not found in the dictionary. If default is not provided, None will be returned when the key is not found.

Example

Let's create a simple dictionary and use the get() method to access its values:

scores = {'Physics': 67, 'Maths': 87, 'History': 75}
result = scores.get('Physics')
print(result) # Output: 67

In this example, we have a dictionary named scores. We use the get() method to access the value associated with the key 'Physics', which is 67. The output will be 67.

Default Values

If you want to provide a default value for when the specified key is not found, you can do so by including the second argument in the get() method:

result = scores.get('Geography', 0)
print(result) # Output: 0 (since 'Geography' is not a key in our dictionary)

In this example, we use the get() method to access the value associated with the key 'Geography'. Since 'Geography' is not a key in our dictionary, it returns the default value of 0.

Using get() for Key Safety

The get() method can also be used to ensure that only existing keys are accessed, preventing potential errors:

scores = {'Physics': 67, 'Maths': 87, 'History': 75}

try:
print(scores.get('Unknown')) # Output: None (since 'Unknown' is not a key in our dictionary)
except KeyError:
print("Key Error: Unknown is not a valid key.")

In this example, we use the get() method with a non-existent key ('Unknown') to demonstrate that it returns None without raising an error. If you want to handle such cases, you can catch the KeyError exception and provide a custom error message.

Worked Example

Let's walk through an example where we use the get() method to create a simple student record system:

student_records = {
'Alice': {'age': 21, 'major': 'Computer Science'},
'Bob': {'age': 20, 'major': 'Electrical Engineering'},
}

def get_student_record(name):
try:
return student_records[name]
except KeyError:
return {"name": name, "error": "Student not found"}

print(get_student_record('Alice')) # Output: {'age': 21, 'major': 'Computer Science'}
print(get_student_record('Charlie')) # Output: {"name": 'Charlie', "error": "Student not found"}

In this example, we have a dictionary student_records that stores student records. We create a function called get_student_record() to access the record of a specific student by name. If the student is found, it returns their record; otherwise, it returns an error message.

Extending the Worked Example

  1. Modify the student_records dictionary in our worked example to include more students and their records. Create functions to add new students, update existing student records, and remove students from the dictionary.
  2. Write a program that uses the get() method to fetch data from an API and handle cases where the requested key is not found or the response is invalid (e.g., non-JSON data).

Common Mistakes

  1. Not providing a default value: When using the get() method and the specified key is not found, an error will be raised if no default value is provided. To avoid this, always include a default value when you're unsure whether the key exists in the dictionary.
  1. Incorrectly handling exceptions: When using the get() method with a default value, it's essential to handle the exception properly. In our worked example, we catch the KeyError and return an error message instead of letting the exception propagate.
  1. Confusing get() with keys(), values(), or items(): The get() method can be easily confused with other dictionary methods like keys(), values(), and items(). Be sure to use the correct method for your needs.

Common Mistakes (continued)

  1. Incorrectly handling exceptions: When using the get() method with a default value, it's essential to handle the exception properly. In our worked example, we catch the KeyError and return an error message instead of letting the exception propagate. However, you may want to consider logging the error or providing more detailed information about the issue for debugging purposes.
  1. Not checking if the default value is needed: When using a default value with the get() method, it's important to check whether the key exists in the dictionary before providing a default value. In some cases, you may want to return an error message instead of using a default value when the key is not found.

Practice Questions

  1. Write a function that takes a dictionary and a key as input and returns the value associated with that key or a default value if it's not found.
  2. Modify the student_records dictionary in our worked example to include more students and their records. Create functions to add new students, update existing student records, and remove students from the dictionary.
  3. Write a program that uses the get() method to fetch data from an API and handle cases where the requested key is not found or the response is invalid (e.g., non-JSON data).
  4. Create a function that takes a list of dictionaries as input and returns a new dictionary containing only the values for specific keys from each sub-dictionary. For example, if the input is:
data = [{'name': 'Alice', 'age': 21, 'major': 'Computer Science'}, {'name': 'Bob', 'age': 20, 'major': 'Electrical Engineering'}]

The function should return:

{'Alice': 'Computer Science', 'Bob': 'Electrical Engineering'}
  1. Write a program that uses the get() method to create a simple command-line interface for managing a dictionary of student records, allowing users to add, update, and remove students by name.

FAQ

  1. Why should I use the get() method instead of accessing dictionary keys directly? Using the get() method allows you to provide a default value when the specified key is not found, reducing the likelihood of runtime errors and making your code more robust.
  2. Can I use the get() method with list and tuple objects in Python? No, the get() method can only be used with dictionaries in Python. For other data structures like lists and tuples, you should use indexing or slicing to access their elements.
  3. Is it possible to use multiple keys to retrieve a value from a dictionary using the get() method? No, the get() method can only retrieve values associated with a single key. To access values based on multiple keys, consider using nested dictionaries or list comprehensions.
  4. How can I check if a key exists in a dictionary without using the get() method? You can use the in operator to check if a key exists in a dictionary:
scores = {'Physics': 67, 'Maths': 87, 'History': 75}
print('Physics' in scores) # Output: True
print('Geography' in scores) # Output: False
  1. What happens when I use the get() method with a key that is not a string? The get() method expects keys to be strings or integers. If you try to use another type as a key, Python will convert it to a string before searching for the key in the dictionary. For example:
scores = {'Physics': 67, 'Maths': 87, 'History': 75}
print(scores.get(1)) # Output: None (since 1 is not a valid key)
get() (Python Programming) | Python | XQA Learn