Add Dictionary Items
What You'll Learn: In this tutorial, you'll discover how to add new items to a dictionary. This helps you expand the data stored in your dictionary.
Adding Items
You can add an item to a dictionary by using a new index key and assigning a value to it.
Example Code:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
What's Happening Here?
thisdict["color"] = "red"adds a new key-value pair to the dictionary.
Updating Dictionary with the update() Method
The update() method updates the dictionary with items from a given argument. If the item does not exist, it will be added.
Example Code:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)
Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
What's Happening Here?
thisdict.update({"color": "red"})adds a new key-value pair to the dictionary if it doesn't exist or updates it if it does.
Try It Yourself: Fun Exercises
- Add More Details to Your Favorite Book:
- Create a dictionary with the title, author, and year of your favorite book.
- Add the genre of the book to the dictionary using both methods.
- Expand Your Snack Inventory:
- Write a dictionary of snacks and their quantities.
- Use the
update()method to add a new snack to the dictionary.
Summary:
In this Python tutorial, we learned how to add new items to a dictionary by assigning values to new keys and using the update() method. These methods allow you to expand and update your dictionary data efficiently. Keep experimenting and have fun with dictionaries in Python!