Lesson 4
Navigating the Nested Wilderness: Mastering Python's Compound Data Structures
Introduction

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.

Recap: Dictionaries, Lists, and Understanding Nested Structures

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:

Python
1# Dicitionary with grades as keys and lists of students as values 2school_directory = { 3 'Grade1': ['Amy', 'Bobby', 'Charlie'], 4 'Grade2': ['David', 'Eve', 'Frank'], 5 'Grade3': ['George', 'Hannah', 'Ivy'] 6} 7 8# Prints the Grade1 list in the dictionary 9print(school_directory['Grade1']) # Output: ['Amy', 'Bobby', 'Charlie']
Creating Nested Dictionaries and Lists

Just like their non-nested versions, creating nested structures is straightforward.

Nested Dictionary:

Python
1# Dictionary within a dictionary 2nested_dict = { 3 'fruit': { 4 'apple': 'red', # key-value pair within the 'fruit' dictionary 5 'banana': 'yellow' # another key-value pair within the 'fruit' dictionary 6 }, 7 'vegetable': { 8 'carrot': 'orange', 9 'spinach': 'green' 10 } 11} 12 13# Prints the nested dictionary 14print(nested_dict)

Nested List:

Python
1# Lists within a list 2nested_list = [ 3 [1, 2, 3], # inner list within the outer list 4 [4, 5, 6], # another inner list within the outer list 5 [7, 8, 9] # third inner list within the outer list 6] 7 8# Prints the nested list 9print(nested_list)

Nested Dictionary and Lists:

Python
1# Lists within a dictionary 2list_dict = { 3 'numbers': [1, 2, 3], # keys associated with lists 4 'letters': ['a', 'b', 'c'] 5} 6 7# Prints the dictionary of lists 8print(list_dict)
Accessing Values in Nested Structures

The retrieval of values from nested dictionaries or lists follows rules similar to those for their non-nested counterparts.

From Nested Dictionary:

Python
1# Dictionary within a dictionary 2nested_dict = { 3 'fruit': { 4 'apple': 'red', # key-value pair within the 'fruit' dictionary 5 'banana': 'yellow' # another key-value pair within the 'fruit' dictionary 6 }, 7 'vegetable': { 8 'carrot': 'orange', 9 'spinach': 'green' 10 } 11} 12 13# Accessing apple's color from nested dictionary 14print(nested_dict['fruit']['apple']) # Output: 'red'

From Nested List:

Python
1# Lists within a list 2nested_list = [ 3 [1, 2, 3], # inner list within the outer list 4 [4, 5, 6], # another inner list within the outer list 5 [7, 8, 9], # third inner list within the outer list 6] 7 8# Accessing the 3rd value from the 2nd list in nested list 9print(nested_list[1][2]) # Output: 6

From Both:

Python
1# Lists within a dictionary 2list_dict = { 3 'numbers': [1, 2, 3], # keys associated with lists 4 'letters': ['a', 'b', 'c'] 5} 6 7# Accessing the second letter in the 'letters' list in list_dict 8print(list_dict['letters'][1]) # Output: 'b'
Common Operations on these Structures

The modification of nested lists and dictionaries is similar to that of non-nested versions.

Python
1# Modifying spinach's color to red 2nested_dict['vegetable']['spinach'] = 'red' 3 4# Adding 10 to the first list in nested list 5nested_list[0].append(10) 6 7# Adding cherry to the 'fruit' dictionary in nested_dict 8nested_dict['fruit']['cherry'] = 'red' 9 10# Deleting the 2nd value from the 3rd list in nested list 11del nested_list[2][1] 12 13# Deleting apple from the 'fruit' dictionary in nested_dict 14del nested_dict['fruit']['apple']
Identifying Errors and Handling Exceptions

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.

Python
1# Trying to print a non-existent key in nested_dict 2try: 3 print(nested_dict['fruit']['mango']) 4except KeyError: 5 print("Key not found!")

In this code:

  • The try block attempts to execute print(nested_dict['fruit']['mango']).
  • If mango does not exist in nested_dict['fruit'], a KeyError is raised.
  • The except KeyError block catches this error and prints "Key not found!" instead of stopping the program execution.
Lesson Summary

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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.