Course Content
Python Data Structures
Python Data Structures
Adding Items to a Dictionary: Updating Key-Value Pairs
Dictionaries are dynamic, meaning you can add, update, or remove items after the dictionary has been created. Let's explore how to add new items to a dictionary.
Start with creating a dictionary called book
with some initial details:
book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813} print(book)
To make our dictionary more complete, we can add a new key-value pair to it. For example, we might want to add the genre
of the book:
book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813} book["genre"] = "Romance" print(book)
After adding the new key-value pair, the dictionary now includes:
Updating an Existing Key-Value Pair
If you need to update the value of an existing key, you can do so by reassigning a new value to that key. For example, let's assume the book's publication year was corrected to 1815
:
book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance"} book["year"] = 1815 print(book)
Note
Single
' '
and double" "
quotes in Python are interchangeable and equivalent.
Swipe to start coding
You are given a dictionary authors_books
and 2 variables: author_to_add
and fitzgeralds_books
.
Your goal:
- Add a new author and their list of books to the
authors_books
dictionary. - The author should be the key, and the list of books should be the value.
Solution
Thanks for your feedback!
Adding Items to a Dictionary: Updating Key-Value Pairs
Dictionaries are dynamic, meaning you can add, update, or remove items after the dictionary has been created. Let's explore how to add new items to a dictionary.
Start with creating a dictionary called book
with some initial details:
book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813} print(book)
To make our dictionary more complete, we can add a new key-value pair to it. For example, we might want to add the genre
of the book:
book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813} book["genre"] = "Romance" print(book)
After adding the new key-value pair, the dictionary now includes:
Updating an Existing Key-Value Pair
If you need to update the value of an existing key, you can do so by reassigning a new value to that key. For example, let's assume the book's publication year was corrected to 1815
:
book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance"} book["year"] = 1815 print(book)
Note
Single
' '
and double" "
quotes in Python are interchangeable and equivalent.
Swipe to start coding
You are given a dictionary authors_books
and 2 variables: author_to_add
and fitzgeralds_books
.
Your goal:
- Add a new author and their list of books to the
authors_books
dictionary. - The author should be the key, and the list of books should be the value.
Solution
Thanks for your feedback!