Add a Key-Value Pair to a Nested Dictionary in Python
Last Updated :
13 Feb, 2024
Dictionaries in Python are versatile data structures that allow you to store and manipulate key-value pairs. When dealing with nested dictionaries, adding a key-value pair becomes a bit more intricate. In this article, we will explore four simple methods to add a key-value pair to a nested dictionary in Python. To illustrate these methods, we will use a student data dictionary.
Add a Key-Value Pair to a Nested Dictionary in Python
Below, are the ways to Add a Key-Value Pair to a Nested Dictionary in Python.
Add Key-Value Pair to Nested Dictionary Using Square Bracket
In this example, below code initializes a nested student data dictionary with information about the name, age, and grades. It then prints the original dictionary. The subsequent line adds a new key-value pair ('science': 95) to the 'grades' dictionary using square bracket notation.
Python3
# Original Student Data Dictionary
student_data = {
'name': 'John Doe',
'age': 20,
'grades': {
'math': 90,
'english': 85,
'history': 78
}
}
print("Original Dictionary\n", student_data)
# Using Square Bracket Notation
student_data['grades']['science'] = 95
print("Using Square Bracket Notation\n", student_data)
Output
Original Dictionary
{'name': 'John Doe', 'age': 20, 'grades': {'math': 90, 'english': 85, 'history': 78}}
Using Square Bracket Notation
{'name': 'John Doe', 'age': 20, 'grades': {'math': 90, 'english': 85, 'history': 78, 'science': 95}}
Add Key-Value Pair to Nested Dictionary Using update()
Method
In this example, below code starts with an original student data dictionary containing information about name, age, and grades. It then prints the original dictionary. The subsequent lines demonstrate updating the 'grades' dictionary using the `update()` method, adding new subjects ('physics': 88, 'chemistry': 92).
Python3
# Original Student Data Dictionary
student_data = {
'name': 'John Doe',
'age': 20,
'grades': {
'math': 90,
'english': 85,
'history': 78
}
}
print("Original Dictionary\n", student_data)
# Using the `update()` Method
new_subjects = {'physics': 88, 'chemistry': 92}
student_data['grades'].update(new_subjects)
print("Using the `update()` Method\n", student_data)
Output
Original Dictionary
{'name': 'John Doe', 'age': 20, 'grades': {'math': 90, 'english': 85, 'history': 78}}
Using the `update()` Method
{'name': 'John Doe', 'age': 20, 'grades': {'math': 90, 'english': 85, 'history': 78, 'physics': 88, 'chemistry': 92}}
Add Key-Value Pair to Nested Dictionary Using setdefault()
In this example, below code begins with an original student data dictionary containing details like name, age, and grades. After printing the original dictionary, it utilizes the `setdefault()` method to add a new subject ('biology': 89) to the 'grades' dictionary, ensuring the key exists or creating it if absent.
Python3
# Original Student Data Dictionary
student_data = {
'name': 'John Doe',
'age': 20,
'grades': {
'math': 90,
'english': 85,
'history': 78
}
}
print("Original Dictionary\n", student_data)
# Using the `setdefault()` Method
student_data.setdefault('grades', {})['biology'] = 89
print("Using the `setdefault()` Method\n", student_data)
Output
Original Dictionary
{'name': 'John Doe', 'age': 20, 'grades': {'math': 90, 'english': 85, 'history': 78}}
Using the `setdefault()` Method
{'name': 'John Doe', 'age': 20, 'grades': {'math': 90, 'english': 85, 'history': 78, 'biology': 89}}
Conclusion
In conclusion, adding a key-value pair to a nested dictionary in Python involves accessing the nested dictionary at the desired level and assigning the new key-value pair. Utilizing the appropriate syntax for dictionary manipulation ensures seamless integration of data into complex nested structures. This straightforward process empowers developers to efficiently expand and modify nested dictionaries, enhancing flexibility and functionality in their Python programs.
Similar Reads
Add a key value pair to Dictionary in Python The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key.For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'fo
3 min read
Python Dictionary Add Value to Existing Key The task of adding a value to an existing key in a Python dictionary involves modifying the value associated with a key that is already present. Unlike adding new key-value pairs, this operation focuses on updating the value of an existing key, allowing us to increment, concatenate or otherwise adju
2 min read
Python - Add Values to Dictionary of List A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Letâs look at some commonly used methods to efficien
3 min read
Python Print Dictionary Keys and Values When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values.Example: Using print() MethodPythonmy_dict = {'a': 1, 'b': 2, 'c': 3} print("Keys:", l
2 min read
Adding Items to a Dictionary in a Loop in Python The task of adding items to a dictionary in a loop in Python involves iterating over a collection of keys and values and adding them to an existing dictionary. This process is useful when we need to dynamically build or update a dictionary, especially when dealing with large datasets or generating k
3 min read