Safe Access with `.get()`
Accessing a missing key with `[]` causes an error! The `.get()` method is safer: it returns `None` (or a default value you specify) if the key isn't found.
Given the dictionary:
Your task: Use the .get()
method to retrieve the value for the key 'oranges'
. If it's missing, return the default value 0
.
Exploring Dictionary Contents
Dictionaries have helpful methods to see their contents. Click the buttons below to see what `.keys()`, `.values()`, and `.items()` (key-value pairs) conceptually return for the example dictionary.
Example Dictionary:
Working with Nested Dictionaries
Dictionaries can contain other dictionaries (or lists!). Access nested values by chaining the square brackets `[]`.
Consider this nested dictionary:
Your task: Write the Python code to access 'Charlie'
's email address.
Advanced Missions!
Apply your knowledge of `.get()`, methods, and nested structures.
Mission 1: Get Status Safely
Assume `server_status = {'ip': '192.168.1.100', 'online': True}` exists. Write one line using `.get()` to print the value of the key 'latency'
. If it's missing, print the default string "unknown"
.
Mission 2: Build Nested Info
Create a dictionary named `project`. It should have a key 'name'
with value 'AI Project'
. It should also have a key 'details'
whose value is *another dictionary* containing 'status'
: 'active'
and 'version'
: 0.1
.
Mission 3: Update Nested Status
Assume the `project` dictionary from Mission 2 exists. Write one line of code to change the nested 'status'
inside 'details'
to 'completed'
.
Module 20 Advanced Practice Complete!
Excellent work! You've explored powerful dictionary methods and handled nested data structures.
Feel free to review the basic practice or watch the video lesson for reinforcement.