Python Dictionaries: Add Dictionary Items

Adding Items to a Python Dictionary

In Python, you can expand a dictionary by introducing new items. This involves specifying a new key and assigning it a value. Let’s explore how to achieve this with some examples related to books.

Adding New Items

To add an item to a dictionary, you simply use a new key and set its value. Here’s how you can do it:

book_dict = {
  "title": "To Kill a Mockingbird",
  "author": "Harper Lee",
  "year": 1960
}

# Adding a new item
book_dict["genre"] = "Fiction"
print(book_dict)

In this example, we’ve added a new entry for the genre of the book. The updated dictionary now includes the new key-value pair.

Updating a Dictionary with the update() Method

The update() method allows you to modify an existing dictionary or add new items if the key does not already exist. This method can take another dictionary or an iterable of key-value pairs as its argument.

Here’s how you can use update() to add or modify items in a dictionary:

book_dict = {
  "title": "1984",
  "author": "George Orwell",
  "year": 1949
}

# Update the dictionary with new items
book_dict.update({"publisher": "Secker & Warburg", "pages": 328})
print(book_dict)

In this case, we used the update() method to add both a publisher and a page count to the dictionary. If the keys did not previously exist, they are added; if they do, their values are updated.

Adding and updating dictionary items is straightforward in Python, making it easy to manage and manipulate your data structures.

Leave a Comment