How to Create Nested Dictionary in Python

How to create a nested dictionary in Python? In this article, I will go over the steps on how to create a nested dictionary in Python. A nested dictionary is a dictionary that contains other dictionaries as its values. This allows you to store data in a hierarchical structure, similar to how you would use nested lists or nested objects in other programming languages.

Quick Examples of Creating Nested Dictionary

Below are some quick examples of how to create a nested dictionary. These should give you an idea of how to create a nested dictionary and the below sections explain in detail.


# Method 1: Create nested dictionary using curly braces {}
nested_dict1 = {
    "Python": {
        "use": "general-purpose"
    },
    "C++": {
        "use": "systems programming"
    }
}

# Method 2: Creating a nested dictionary using the dict() 
nested_dict2 = dict(Python=dict(use="general-purpose"),
                   C=dict(use="systems programming"))

# Method 3: Creating using a dictionary comprehension
nested_dict3 = {language: { "use": use} for language,
                use in [("Python", "general-purpose"), 
                        ("C++", "systems programming")]
                }

# Method 4: Creating using the update() method
nested_dict4 = {}
nested_dict4.update(Python=dict(use="general-purpose"), 
                    C=dict(use="systems programming"))

# Method 5: Nested dictionary from a JSON object
import json
json_str = '''{"Python": {"use": "general-purpose"}, 
              "C++": {"use": "systems programming"}}'''
nested_dict5 = json.loads(json_str)

1. Create Nested Dictionary using {} Notation

One of the most straightforward methods for creating a nested dictionary in Python is using the curly braces {} notation. It allows you to specify the keys and values of the dictionary using a simple syntax. In the case of a nested dictionary, you can create a dictionary with keys that point to dictionaries as values.

1.1 Syntax Using Curly Braces {}

To create a dictionary using the curly braces {} notation, you can use the following syntax:


# Syntax using curly {}
nested_dict = {
    key1: {
        inner_key1: inner_value1,
        inner_key2: inner_value2,
        ...
    },
    key2: {
        inner_key1: inner_value1,
        inner_key2: inner_value2,
        ...
    },
    ...
}

1.2 Create Nested Dictionary Example

The example creates a nested dictionary called languages with three keys: “Py”, “Java”, and “C#”. Each of these keys points to another dictionary as its value. The nested dictionary can be accessed and modified using the keys and the dot notation.


# Create nested dictionary
languages = {
    "Py": {
        "year": 1991,
        "creator": "G. van Rossum",
    },
    "Java": {
        "year": 1995,
        "creator": "J. Gosling",
    },
    "C#": {
        "year": 2000,
        "creator": "Microsoft",
    }
}
print(languages )

2. Creating Nested Dictionary Using dict() Constructor

The dict() constructor is a built-in function in Python that allows you to create a dictionary. It can be used to create a nested dictionary by providing it with key-value pairs where the values are dictionaries themselves.

Check an example of creating a nested dictionary that stores information about different programming languages using the dict() constructor:


# Create using dict()
languages = dict(
    Py=dict(year=1991, creator="G. van Rossum"),
    Java=dict(year=1995, creator="J. Gosling"),
    C_Sharp=dict(year=2000, creator="Microsoft")
)
print(languages)

3. Creating Nested Dictionary Using Comprehension

A dictionary comprehension allows you to create a dictionary by specifying the keys and values using a single line of code. You can also use dictionary comprehension to create a nested dictionary, which is a dictionary that has keys that point to dictionaries as values.


# Create using Dictionary Comprehension
languages = {
    language: { "year": year, "creator": creator}
    for language, year, creator in [
        ("Py", 1991, "G. van Rossum"),
        ("Java", 1995, "J. Gosling"),
        ("C#", 2000, "Microsoft")
    ]
}
print(languages)

4. Using update() Method

The update() method is a built-in method in Python that allows you to update the keys and values of a dictionary that can also be used to create a nested dictionary. It takes a dictionary as an argument and adds the key-value pairs of that dictionary to the original dictionary.


# Update update() Method
languages = {}

languages.update({"Py": {"year": 1991, "creator": "G. van Rossum"}})
languages.update({"Java": {"year": 1995, "creator": "J. Gosling"}})
languages.update({"C#": {"year": 2000, "creator": "Microsoft"}})

print(languages)

5. Creating from a JSON Object

If you are creating a nested dictionary from JSON, you can use the json.loads() method to create a nested dictionary from a JSON object that has nested keys and values. The json.loads() method is a built-in method in Python that allows you to parse a JSON string and create a dictionary from it.


# From json file
import json

json_string = '''{
  "Python": {"year": 1991, "creator": "G. van Rossum"},
  "Java": {"year": 1995, "creator": "J. Gosling"},
  "C#": {"year": 2000, "creator": "Microsoft"}
  }'''
languages = json.loads(json_string)

print(languages) 

6. Common Operations on Nested Dictionary in Python

A nested dictionary is a dictionary that has keys that point to dictionaries as values. Once you have created a nested dictionary, you may want to perform various operations on it, such as accessing, modifying, adding, and deleting elements.

These are some of the examples of operations that are most common.


# Accessing elements of a nested dictionary
print(languages["Py"]["year"])  

# Output: 
# 1991

# Modifying elements in a nested dictionary
languages["Py"]["year"] = 1992

# Adding new elements to a nested dictionary
languages["Py"]["use"] = "web development"

# Deleting elements from a nested dictionary
del languages["Py"]["use"]

# Looping through a nested dictionary
for outer_key, inner_dict in languages.items():
    for inner_key, value in inner_dict.items():
        print(f"{outer_key}.{inner_key}: {value}")

Besides these there are several Python Dictionary Methods that are used to perform operations on nested dictionaries.

Summary and Conclusion

In this article, you have learned about how to create a nested dictionary in Python using various methods. If you have any questions about creating or working with nested dictionaries in Python, feel free to ask! I will do my best to help.

AlixaProDev

I am a software Engineer with extensive 4+ years of experience in Programming related content Creation.

Leave a Reply