Accessing Dictionary Values
Let's build a dictionary to represent a book in a library:
12book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813} print(book)
This dictionary includes three key-value pairs:
In a dictionary, you can retrieve an item by referencing its key. Here's an example of accessing the publication year of the book:
1234book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813} publication_year = book["year"] print(publication_year) # Output: 1813
In the code provided:
- Python searches for the key
"year"
in the book dictionary; - It retrieves the value associated with the key (
1813
) and assigns it to the variablepublication_year
.
The value is then printed, demonstrating how keys allow quick and specific access to dictionary values.
Swipe to start coding
You are given a dictionary authors_books
where the book author is the key and the list of book titles is the value.
- Initialize the variable
kings_books
as a list of Stephen King's books. - Initialize the variable
shakspeares_books
as a list of Shakespeare's books. - You should initialize the variables by getting the data from the dictionary using the key.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 3.23
Accessing Dictionary Values
Swipe to show menu
Let's build a dictionary to represent a book in a library:
12book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813} print(book)
This dictionary includes three key-value pairs:
In a dictionary, you can retrieve an item by referencing its key. Here's an example of accessing the publication year of the book:
1234book = {"title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813} publication_year = book["year"] print(publication_year) # Output: 1813
In the code provided:
- Python searches for the key
"year"
in the book dictionary; - It retrieves the value associated with the key (
1813
) and assigns it to the variablepublication_year
.
The value is then printed, demonstrating how keys allow quick and specific access to dictionary values.
Swipe to start coding
You are given a dictionary authors_books
where the book author is the key and the list of book titles is the value.
- Initialize the variable
kings_books
as a list of Stephen King's books. - Initialize the variable
shakspeares_books
as a list of Shakespeare's books. - You should initialize the variables by getting the data from the dictionary using the key.
Solution
Thanks for your feedback!
Awesome!
Completion rate improved to 3.23single