Ask Your Question
1

What is the technique for adding values into a python dictionary that is nested?

asked 2023-04-04 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-08-26 09:00:00 +0000

bukephalos gravatar image

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}}}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-04 11:00:00 +0000

Seen: 8 times

Last updated: Aug 26 '21