Course Content
Python Data Structures
Python Data Structures
Accessing Dictionary Keys
To access the keys of a dictionary in Python, you can use the keys()
method. This returns a view object that displays all the keys in the dictionary.
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance" } keys = book.keys() print(keys) # Output: dict_keys(['title', 'author', 'year', 'genre'])
Iterating Through Keys
You can iterate through the keys in a dictionary using a for
loop:
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance" } for key in book.keys(): print(key)
Checking for the Existence of a Key
Use the in keyword to check if a specific key exists in the dictionary:
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance" } if "author" in book: print("The 'author' key exists in the dictionary.")
Swipe to start coding
You are given a dictionary authors_books
, where the key is the author and the value is a list of their book titles.
Your goal:
- Initialize the variable
keys
as a list of the dictionary keys. - Initialize the variable
all_books
as a list of all available book titles. - Use a
for
loop to get the book lists by author. - Use a nested
for
loop and theappend()
method to fill theall_books
list with all available books.
Solution
Thanks for your feedback!
Accessing Dictionary Keys
To access the keys of a dictionary in Python, you can use the keys()
method. This returns a view object that displays all the keys in the dictionary.
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance" } keys = book.keys() print(keys) # Output: dict_keys(['title', 'author', 'year', 'genre'])
Iterating Through Keys
You can iterate through the keys in a dictionary using a for
loop:
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance" } for key in book.keys(): print(key)
Checking for the Existence of a Key
Use the in keyword to check if a specific key exists in the dictionary:
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance" } if "author" in book: print("The 'author' key exists in the dictionary.")
Swipe to start coding
You are given a dictionary authors_books
, where the key is the author and the value is a list of their book titles.
Your goal:
- Initialize the variable
keys
as a list of the dictionary keys. - Initialize the variable
all_books
as a list of all available book titles. - Use a
for
loop to get the book lists by author. - Use a nested
for
loop and theappend()
method to fill theall_books
list with all available books.
Solution
Thanks for your feedback!