Course Content
Python Data Structures
Python Data Structures
Accessing Dictionary Values
Let's build a dictionary to represent a book in a library:
book = {"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:
book = {"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 show code editor
Print the title of the book and the year it was published from the book
dictionary. Use key indexing to retrieve the information.
Thanks for your feedback!
Accessing Dictionary Values
Let's build a dictionary to represent a book in a library:
book = {"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:
book = {"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 show code editor
Print the title of the book and the year it was published from the book
dictionary. Use key indexing to retrieve the information.
Thanks for your feedback!