Add a new item to a dictionary in Python

To add a new item (key-value pair) to a dictionary in Python, you can use the square brackets [] or the update() method. Here's an example using square brackets:

# Initialize an empty dictionary
my_dict = {}

# Add a new item to the dictionary
my_dict["new_key"] = "new_value"

# Print the dictionary
print(my_dict)

This will output {'new_key': 'new_value'}.

Watch a course Python - The Practical Guide

Here's an example using the update() method:

# Initialize an empty dictionary
my_dict = {}

# Add a new item to the dictionary
my_dict.update({"new_key": "new_value"})

# Print the dictionary
print(my_dict)

This will also output {'new_key': 'new_value'}.