Skip to content

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:

Assign a new item to a dictionary in Python

python
# 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'}.

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

Update a dictionary in Python and add a new item to it

python
# 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'}.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.