0
0
Pythonprogramming~5 mins

Safe access using get() in Python

Choose your learning style9 modes available
Introduction

Sometimes, you want to get a value from a dictionary without causing an error if the key is missing. The get() method helps you do this safely.

When you want to read a value from a dictionary but are not sure if the key exists.
When you want to provide a default value if the key is missing.
When you want to avoid your program crashing due to missing keys.
When you want cleaner and simpler code instead of using if-else checks.
Syntax
Python
dictionary.get(key, default_value)

key is the item you want to find in the dictionary.

default_value is optional. It is returned if the key is not found. If you don't provide it, None is returned by default.

Examples
Gets the value for 'age'. Since 'age' exists, it returns 30.
Python
person = {'name': 'Alice', 'age': 30}
age = person.get('age')
Tries to get 'city'. Since it doesn't exist, returns 'Unknown' instead of error.
Python
person = {'name': 'Alice', 'age': 30}
city = person.get('city', 'Unknown')
Tries to get 'city'. Since it doesn't exist and no default is given, returns None.
Python
person = {'name': 'Alice', 'age': 30}
city = person.get('city')
Sample Program

This program safely gets 'name' and 'city' from the dictionary. 'name' exists, so it prints 'Bob'. 'city' does not exist, so it prints the default 'Not specified'.

Python
person = {'name': 'Bob', 'age': 25}

# Safe access with get()
name = person.get('name')
city = person.get('city', 'Not specified')

print(f"Name: {name}")
print(f"City: {city}")
OutputSuccess
Important Notes

Using get() avoids errors when keys are missing.

If you forget the default value, get() returns None, which you can check for.

This method works only with dictionaries, not with lists or other data types.

Summary

get() helps you safely access dictionary values without errors.

You can provide a default value to use if the key is missing.

This makes your code cleaner and safer when working with dictionaries.