+ 4

Can help to explain the steps for these?

So basically theres this question involving lessons on dictionary but I'm very confused on how to use the .get function, so can anyone help to explain how to use the function in this case. This is the initial code: books = { "Life of Pi": "Adventure Fiction", "The Three Musketeers": "Historical Adventure", "Watchmen": "Comics", "Bird Box": "Horror", "Harry Potter":"Fantasy Fiction", "Good Omens": "Comedy" } book = input() #change this part to use the .get() method if(book in books): print(books[book]) else: print("Book not found") Rewrite the given code to use the .get() method instead of the if/else statements. Also, change the output to "Book not found", when the book is not found.

14th Apr 2021, 4:02 AM
Zhi Hong
Zhi Hong - avatar
5 Answers
+ 9
books.get(book,"Book not found")
14th Apr 2021, 4:03 AM
Илья Мирошник
Илья Мирошник - avatar
+ 5
Return book and in default if book don't exist return Book not found
14th Apr 2021, 4:04 AM
Илья Мирошник
Илья Мирошник - avatar
0
Илья Мирошник ohhh was thinking of that but got confused thanks for clearing it up for me appreciated it man!
14th Apr 2021, 4:12 AM
Zhi Hong
Zhi Hong - avatar
0
print (books.get(book,"Book not found")) #if book in books => print original value #if book not in books => creat a new key(book):value
27th Apr 2021, 2:09 PM
張立威
張立威 - avatar
0
The correct code is: books = { "Life of Pi": "Adventure Fiction", "The Three Musketeers": "Historical Adventure", "Watchmen": "Comics", "Bird Box": "Horror", "Harry Potter":"Fantasy Fiction", "Good Omens": "Comedy" } book = input() if(book in books): genre = books.get(book) print(genre) else: print("Book not found")
20th Jan 2022, 6:38 PM
Nicholas