Update Nested Dictionary - Python
Last Updated :
29 Jan, 2025
A nested dictionary in Python is a dictionary that contains another dictionary (or dictionaries) as its value. Updating a nested dictionary involves modifying its structure or content by:
- Adding new key-value pairs to any level of the nested structure.
- Modifying existing values associated with specific keys.
- Removing key-value pairs from any level within the nested structure.
Direct Assignment
Direct assignment is the most straightforward method to update a nested dictionary. We access the nested key directly and assign a new value to it.
Example:
Python
# Initial nested dictionary
d = {
"name": "Bob",
"age": 20,
"grades": {
"math": "A",
"science": "B"
}
}
# Updating the science grade to 'A'
d["grades"]["science"] = "A"
print(d)
Output{'name': 'Bob', 'age': 20, 'grades': {'math': 'A', 'science': 'A'}}
Explanation:
- Accessing Nested Keys: student["grades"]["science"] accesses the science grade within the grades dictionary.
- Assigning New Value: By setting it equal to "A", we update the existing grade from "B" to "A".
Nested Dictionary Structure:

Below are all the primary methods to update nested dictionaries:
Using the .update() Method (For shallow Nested)
The .update() method allows us to update multiple key-value pairs at once. It can be used on the nested dictionary to add new entries or modify existing. It is used for simple updates to shallow or moderately nested dictionaries.
Example:
Python
# Initial nested dictionary
d = {
"name": "Bob",
"age": 20,
"grades": {
"math": "A",
"science": "B"
}
}
# Adding a new subject 'history' with grade 'A-'
d["grades"].update({"history": "A-"})
print(d)
Output{'name': 'Bob', 'age': 20, 'grades': {'math': 'A', 'science': 'B', 'history': 'A-'}}
Explanation:
- Using .update(): The update() method takes a dictionary as an argument and adds its key-value pairs to the target dictionary.
- Adding New Entry: Here, {"history": "A-"} is added to the grades dictionary.
Using setdefault()
setdefault() method is useful for ensuring that a key exists in the dictionary. If the key doesn't exist, it initializes it with a default value. This method can be chained to handle multiple nested levels. It can also be used when we need to initialize a default value for a key that may not exist.
Example:
Python
# Initial nested dictionary
d = {
"name": "Bob",
"age": 20,
"grades": {
"math": "A",
"science": "B"
}
}
# Ensuring 'contact' dictionary exists and adding 'email'
d.setdefault("contact", {}).setdefault("email", "[email protected]")
print(d)
Output{'name': 'Bob', 'age': 20, 'grades': {'math': 'A', 'science': 'B'}, 'contact': {'email': '[email protected]'}}
Explanation:
- First setdefault("contact", {}): Checks if the key "contact" exists. If not, initializes it as an empty dictionary.
- Second setdefault("email", "[email protected]"): Within the "contact" dictionary, checks for the key "email". If absent, sets it to "[email protected]".
Using defaultdict (For Deeply Nested)
The defaultdict from Python's collections module automatically initializes nested dictionaries, eliminating the need to check for key existence manually. It's ideal for deeply nested or dynamically growing dictionaries.
Example:
Python
from collections import defaultdict
# Creating a nested defaultdict
d = defaultdict(dict)
# Adding grades
d["grades"]["math"] = "A"
d["grades"]["science"] = "B"
# Adding contact information
d["contact"]["email"] = "[email protected]"
print(dict(d))
Output{'grades': {'math': 'A', 'science': 'B'}, 'contact': {'email': '[email protected]'}}
Explanation:
- defaultdict(dict): Initializes a dictionary where each value is another dictionary by default.
- Automatic Initialization: When accessing student["grades"] or student["contact"], if these keys don't exist, they are automatically created as empty dictionaries.
Using Dictionary Unpacking (Python 3.5+)
Dictionary unpacking allows us to merge dictionaries or update specific parts by unpacking them into a new dictionary. This method is useful when merging or updating shallow dictionaries with clear input data and situations where immutability of the original dictionaries is preferred.
Example:
Python
# Initial nested dictionary
d1 = {
"name": "Bob",
"age": 20,
"grades": {
"math": "A",
"science": "B"
}
}
# New grades to update
d2 = {
"science": "A",
"history": "A-"
}
# Updating grades using dictionary unpacking
d1["grades"] = {**d1["grades"], **d2}
print(d1)
Output{'name': 'Bob', 'age': 20, 'grades': {'math': 'A', 'science': 'A', 'history': 'A-'}}
Explanation:
- **d1["grades"] and **d2: Unpacks both dictionaries.
- Merging Dictionaries: Keys in d2 overwrite those in student["grades"] if they exist; otherwise, they are added.
- Assigning Back: The merged dictionary is assigned back to student["grades"].
Using the Merge (|) Operator (Python 3.9+)
Python 3.9 introduced the merge (|) operator for dictionaries, allowing us to combine dictionaries to create a new dictionary. This operator can be used to update nested dictionaries by merging inner dictionaries.
Example:
Python
# Initial nested dictionary
d1 = {
"name": "Bob",
"age": 20,
"grades": {
"math": "A",
"science": "B"
}
}
# New grades to update
d2 = {
"science": "A",
"history": "A-"
}
# Updating grades using the merge operator
d1["grades"] = d1["grades"] | d2
print(d1)
Output:
{'name': 'Bob', 'age': 20, 'grades': {'math': 'A', 'science': 'A', 'history': 'A-'}}
Explanation:
- d1["grades"] | d2: Merges d2 into d1["grades"] with d2 taking precedence.
- Assigning Back: The merged dictionary replaces the original d1["grades"].
Similar Reads
Python Dictionary setdefault() Method
Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary. Python Dictionary setdefault() Method Syntax: Syntax: dict.setdefault(key, default_value)Parameters: It takes two parameters: key - Key to be sear
2 min read
Python Dictionary Methods
Python dictionary methods is collection of Python functions that operates on Dictionary.Python Dictionary is like a map that is used to store data in the form of a key: value pair. Python provides various built-in functions to deal with dictionaries. In this article, we will see a list of all the fu
5 min read
Python Counter.update() Method
Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In
2 min read
Python Dictionary get() Method
Python Dictionary get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).Python Dictionary get() Method Syntax:Syntax : Dict.get(key, Value)Parameters: key: The key name of the item you want to return
3 min read
Python Dictionary Exercise
Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
3 min read
Python dictionary values()
values() method in Python is used to obtain a view object that contains all the values in a dictionary. This view object is dynamic, meaning it updates automatically if the dictionary is modified. If we use the type() method on the return value, we get "dict_values object". It must be cast to obtain
2 min read
Python Dictionary keys() method
keys() method in Python dictionary returns a view object that displays a list of all the keys in the dictionary. This view is dynamic, meaning it reflects any changes made to the dictionary (like adding or removing keys) after calling the method. Example:Pythond = {'A': 'Geeks', 'B': 'For', 'C': 'Ge
2 min read
Update List in Python
In Python Programming, a list is a sequence of a data structure that is mutable. This means that the elements of a list can be modified to add, delete, or update the values. In this article we will explore various ways to update the list. Let us see a simple example of updating a list in Python.Pyth
2 min read
Python Dictionary items() method
items() method in Python returns a view object that contains all the key-value pairs in a dictionary as tuples. This view object updates dynamically if the dictionary is modified.Example:Pythond = {'A': 'Python', 'B': 'Java', 'C': 'C++'} # using items() to get all key-value pairs items = d.items() p
2 min read
Convert Lists to Nested Dictionary - Python
The task of converting lists to a nested dictionary in Python involves mapping elements from multiple lists into key-value pairs, where each key is associated with a nested dictionary. For example, given the lists a = ["gfg", "is", "best"], b = ["ratings", "price", "score"], and c = [5, 6, 7], the g
3 min read