Welcome to our exploration of Compound Data Structures in Python. Having navigated through Dictionaries
, Sets
, and Tuples
, we'll delve into nested dictionaries
and lists
. These structures enable us to handle complex and hierarchical data, which is typical in real-world scenarios. This lesson will guide you through a recap of the basics, the creation and modification of nested dictionaries and lists, as well as common error handling.
As a quick recap, Lists
are mutable, ordered collections, while Dictionaries
are collections of key-value pairs. These structures can be nested. Here's a simple example of a school directory:
Just like their non-nested versions, creating nested structures is straightforward.
Nested Dictionary:
Nested List:
Nested Dictionary and Lists:
The retrieval of values from nested dictionaries
or lists
follows rules similar to those for their non-nested counterparts.
From Nested Dictionary:
From Nested List:
From Both:
The modification of nested lists
and dictionaries
is similar to that of non-nested versions.
Python executes exceptions effortlessly by providing the try
/except
blocks. The try
block lets you test a block of code for errors, and the except
block lets you handle the error. In the following example, we attempt to print a non-existent key in nested_dict
. If the key is not found, a KeyError
is raised, and the except
block catches this error and executes its code.
In this code:
- The
try
block attempts to executeprint(nested_dict['fruit']['mango'])
. - If
mango
does not exist innested_dict['fruit']
, aKeyError
is raised. - The
except KeyError
block catches this error and prints "Key not found!" instead of stopping the program execution.
Bravo! You've made a journey through nested lists
and dictionaries
, terms that are becoming increasingly common in the data-intensive programming world. We've learned how to create, access, and modify values in these complex structures and how to handle errors.
Up next, we have hands-on practice sessions to solidify your understanding of these concepts. Hold on to your hats!
