Skip to content

Python update nested dictionary | Example code

  • by

The dictionaries within a dictionary are called a Nested dictionaries in Python. You can update the nested dictionary using the assignment operator or update method in Python.

Yes, updating the Nested dictionary is similar to updating a simple dictionary. Here’s the syntax for updating a nested dictionary in Python:

nested_dict[key1][key2] = new_value

In the above syntax:

  • nested_dict refers to the original nested dictionary.
  • key1 is the outer key of the nested dictionary.
  • key2 is the inner key within key1.
  • new_value is the value you want to assign to the specified key within the nested dictionary.

Example update nested dictionary in Python

Simple example code.

Appending nested list

It will add a new key value to a dictionary.

Employee = {
    'emp1': {
        'name': 'John',
        'age': '29',
        'Designation': 'Programmer'
    },
    'emp2': {
        'name': 'Steve',
        'age': '45',
        'Designation': 'HR'
    }
}

Employee['name'] = 'Kate'

print(Employee)

Output:

{’emp1′: {‘name’: ‘John’, ‘age’: ’29’, ‘Designation’: ‘Programmer’}, ’emp2′: {‘name’: ‘Steve’, ‘age’: ’45’, ‘Designation’: ‘HR’}, ‘name’: ‘Kate’}

Updating existing key values in the Nested dictionary.

This example updates the value for the mentioned key if it is present in the dictionary. Otherwise, it creates a new entry.

Employee = {
    'emp1': {
        'name': 'John',
        'age': '29',
        'Designation': 'Programmer'
    },
    'emp2': {
        'name': 'Steve',
        'age': '45',
        'Designation': 'HR'
    }
}
Employee['emp1']['name'] = 'Kate'
print(Employee)

Output:

Python update nested dictionary

Comment if you have any doubts or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *