Change Dictionary Items

 

What You'll Learn: In this tutorial, you'll discover how to change the values of items in a dictionary. This helps you update information efficiently.

Changing Values

You can change the value of a specific item by referring to its key name.

Example Code:

python
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018
print(thisdict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

What's Happening Here?

  • thisdict["year"] = 2018 changes the value of the "year" key to 2018.

Updating Dictionary with update() Method

The update() method updates the dictionary with items from the given argument. The argument must be a dictionary or an iterable object with key-value pairs.

Example Code:

python
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})
print(thisdict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

What's Happening Here?

  • thisdict.update({"year": 2020}) updates the value of the "year" key to 2020.

Try It Yourself: Fun Exercises

  1. Update Your Favorite Movies:
    • Create a dictionary with movies and their release years.
    • Change the release year of a specific movie using both methods.
  2. Modify Your Snack Inventory:
    • Write a dictionary of snacks and their quantities.
    • Use the update() method to change the quantity of a specific snack.

Summary:

In this Python tutorial, we learned how to change dictionary items by referring to their key names and using the update() method. These methods allow you to keep your dictionary data up-to-date efficiently. Keep experimenting and have fun with dictionaries in Python!