Create a Nested Dictionary in Python

A nested dictionary is a dictionary that contains one or more dictionaries as its values. In this blog post, we will explore different methods to create a nested dictionary in Python.

Method 1: Using Literal Syntax

# Method 1: Using Literal Syntax
my_dict = {"name": "John", "age": 30, "address": {"city": "New York", "country": "USA"}}
print("Nested dictionary:", my_dict)

Output:

Nested dictionary: {‘name’: ‘John’, ‘age’: 30, ‘address’: {‘city’: ‘New York’, ‘country’: ‘USA’}}

Method 2: Using Dictionary Comprehension

# Method 2: Using Dictionary Comprehension
my_dict = {key: {"name": "John", "age": 30} for key in ["A", "B", "C"]}
print("Nested dictionary:", my_dict)

Output:

Nested dictionary: {‘A’: {‘name’: ‘John’, ‘age’: 30}, ‘B’: {‘name’: ‘John’, ‘age’: 30}, ‘C’: {‘name’: ‘John’, ‘age’: 30}}