Section 2. Chapter 3
single
Accessing Dictionary Keys
Swipe to show menu
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.
12345678book = { "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:
123456789book = { "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:
123456789book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance" } if "author" in book: print("The 'author' key exists in the dictionary.")
Task
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.
- Initialize the variable
keysas a object of the dictionary keys. - Initialize the variable
all_booksas a list of all available book titles. - Use a
forloop to get the book lists by author. - Use a nested
forloop and theappend()method to fill theall_bookslist with all available books.
Solution
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 3
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat