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 [].
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:
Add a new key-value pair to a dictionary in Python using the update method
# 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}
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also use the update() method to add multiple key-value pairs at once:
Add multiple new key-value pairs to a dictionary in Python using the update method
my_dict.update({'name': 'John', 'age': 30, 'city': 'New York'})
print(my_dict) # {'name': 'John', 'age': 30, 'city': 'New York'}