Welcome back! You've started with Python dictionaries; now, let's dive deeper. In this unit, we're exploring nested dictionaries - think of them as a multi-level travel guide with detailed information on various destinations.
Moving beyond the basic key-value pairs, we'll focus on nested dictionaries. Imagine organizing airports worldwide, with codes, locations, and amenities, all within nested structures. We'll cover:
- Creating nested dictionaries for structured, multi-level data organization.
- Accessing, manipulating, and updating data within these complex structures.
- Adding new information efficiently.
Nested dictionaries have other dictionaries as values:
Python1# Nested dictionary 2airport_codes = { 3 "JFK": {"city": "New York", "country": "USA"}, 4 "LAX": {"city": "Los Angeles", "country": "USA"} 5} 6
As you can see in the example above, the airport_codes
dictionary has keys "JFK"
and "LAX"
whose values are other dictionaries with their own key-value pairs.
Values can be accessed, added and updated:
Python1airport_codes = { 2 "JFK": {"city": "New York", "country": "USA"}, 3 "LAX": {"city": "Los Angeles", "country": "USA"} 4} 5 6# Add Osaka's Kansai International Airport 7airport_codes["KIX"] = {"city": "Osaka", "country": "Japan"} 8 9# Add airport elevation data to KIX 10airport_codes["KIX"]["elevation"] = 4 11 12# Update elevation data 13airport_codes["KIX"]["elevation"] = 5 14 15# Delete elevation data 16del airport_codes["KIX"]["elevation"]
Nested dictionaries are vital for managing intricate, hierarchical data, crucial for applications like our travel scenario. Understanding these advanced techniques enables sophisticated data modeling and improves problem-solving skills in real-world, data-rich environments.
Let's explore the power and potential of nested data structuring in Python through practice.