Python Dictionaries: Change Dictionary Items

Modifying Dictionary Items in Python

In Python, you can easily update dictionary values by referring to their keys. Let’s explore how you can make changes to the values of specific items in a dictionary.

Updating Values

You can modify the value associated with a specific key by directly referencing the key name. Here’s how you can change the value:

python
# Example dictionary representing a book
book_dict = {
  "title": "1984",
  "author": "George Orwell",
  "year_published": 1949
}

# Change the year_published to 1950
book_dict["year_published"] = 1950

print(book_dict)

In this example, we have updated the "year_published" key to a new value. This method allows you to directly set the value associated with any key in your dictionary.

Updating the Dictionary with the update() Method

The update() method allows you to modify a dictionary by merging in key-value pairs from another dictionary or iterable. This method is quite versatile and can be used to add or change multiple items at once.

python
# Example dictionary representing a book
book_dict = {
  "title": "1984",
  "author": "George Orwell",
  "year_published": 1949
}

# Update the year_published and add a new key-value pair
book_dict.update({"year_published": 1950, "genre": "Dystopian"})

print(book_dict)

In this example, the update() method is used to modify the "year_published" value and add a new "genre" key. The argument passed to update() can be another dictionary or an iterable of key-value pairs.

Using these methods, you can efficiently manage and modify the data within your Python dictionaries, making it easier to keep your data organized and up-to-date.

Leave a Comment

Simple, privacy focused and free ad network for websites in need of new visitors. Free & easy backlink link building. Handing emergencies by domestic helper | 健樂護理有限公司 kl home care ltd.