How can I add new keys to a dictionary?

To add a new key-value pair to a dictionary in Python, you can use the update() method or simply assign a value to a new key using square brackets [].

Here's an example:

# Create an empty dictionary
my_dict = {}

# Add a new key-value pair using the update() method
my_dict.update({'name': 'John'})

# Add a new key-value pair using square brackets
my_dict['age'] = 30

print(my_dict)  # {'name': 'John', 'age': 30}

Watch a course Python - The Practical Guide

You can also use the update() method to add multiple key-value pairs at once:

my_dict.update({'name': 'John', 'age': 30, 'city': 'New York'})
print(my_dict)  # {'name': 'John', 'age': 30, 'city': 'New York'}