capypad
0 day streak
python / beginner
Snippet

Dictionary Key-Value Access

Dictionaries store data in key-value pairs. Using .get() is safer than square brackets because it returns a default value if the key is missing.

snippet.py
python
1
2
user = {'id': 1, 'name': 'Bob'}
print(user.get('name', 'Unknown'))
Breakdown
1
user = {'id': 1, 'name': 'Bob'}
Creates a dictionary with two keys: id and name.
2
user.get('name', 'Unknown')
Attempts to retrieve the value for 'name'. If it doesn't exist, it returns 'Unknown'.