5.1.3 Safe Access with get()

Unit: Unit 5: Dictionaries and Sets • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Safely retrieve values with fallback defaults using get()
user_settings = {
    "theme": "dark",
    "font_size": 14,
    "notifications": True
}

# 1. Access an existing key with get()
current_theme = user_settings.get("theme")

# 2. Access a missing key with default None
sound_volume = user_settings.get("volume")

# 3. Access a missing key with a specified fallback default
language = user_settings.get("language", "en-US")

print("Theme:", current_theme)
print("Volume setting:", sound_volume)
print("Interface Language:", language)
Open in Live Interactive Python Sandbox →