How To Create A Nested Dictionary In Python

In this tutorial, we will learn how to create a nested dictionary in Python. A dictionary in Python is a mutable, unordered collection of key-value pairs, whereas a nested dictionary is a collection of dictionaries within another dictionary.

Nested dictionaries are useful to store complex data structures where simple key-value pairs aren’t sufficient, such as representing a hierarchical tree-like structure.

Step 1: Create a Simple Dictionary in Python

Before diving into nested dictionaries, let us create a simple dictionary in Python. Here’s how to create a dictionary with three key-value pairs:

You can access the values in a dictionary using its keys:

Step 2: Creating a Nested Dictionary

To create a nested dictionary, we add dictionaries within the outer dictionary as values instead of simple data types. For example, if we want to include an “Address” key in the previous dictionary, we can create another dictionary with address-related keys:

Now, the “Address” key has its dictionary with three keys – “Street”, “City”, and “Zip”.

Step 3: Accessing Values in a Nested Dictionary

To access the values in a nested dictionary, we use the outer dictionary key first followed by the inner dictionary key. Here’s an example:

If you are not sure whether a key exists in the outer or inner dictionary, you can use the get() method instead:

This method returns None if the key doesn’t exist in the dictionary, which can be useful to avoid KeyError exceptions.

Step 4: Adding Values to a Nested Dictionary

To add values to a nested dictionary, you need to specify both the outer and inner dictionary keys. Here’s how to add a “Country” key to the “Address” dictionary:

Now the nested dictionary contains the new “Country” key with the value “USA”.

Full Example Code

Output

John Doe
123 Main St
123 Main St

Conclusion

In this tutorial, we learned to create a nested dictionary in Python, access its values, and add new values to it. Nested dictionaries are a helpful data structure to represent complex hierarchical structures and should be used when simple key-value pairs are not sufficient.

With an understanding of how nested dictionaries work, you’re a step closer to handling more complex data in your Python projects.