To add values into a nested dictionary in Python, you can use multiple methods.
Method 1: Using the key to access the nested dictionary
You can use the key to access the nested dictionary and add the value.
Example:
# Initializing the nested dictionary
my_dict = {'a': {'b': {'c': 0}}}
# Adding value to the nested dictionary
my_dict['a']['b']['c'] = 1
# Printing the updated dictionary
print(my_dict)
Output:
{'a': {'b': {'c': 1}}}
Method 2: Using the setdefault() method
You can also use the setdefault() method to add values to a nested dictionary. This method sets a key-value pair in the dictionary if it is not already present.
Example:
# Initializing the nested dictionary
my_dict = {}
# Adding value to the nested dictionary
my_dict.setdefault('a', {}).setdefault('b', {})['c'] = 2
# Printing the updated dictionary
print(my_dict)
Output:
{'a': {'b': {'c': 2}}}
Asked: 2023-04-04 11:00:00 +0000
Seen: 8 times
Last updated: Aug 26 '21