【发布时间】:2020-08-01 11:46:15
【问题描述】:
我有初始代码:
books = []
def add_book():
name = input('Input the name of the book: ')
author = input('Input the author: ')
print('Book added successfully.')
books.append(
{
'name': name,
'author': author,
'read': False
}
)
我需要用户能够提供书名,如果他的输入与books 中的名称匹配,则删除它所引用的整个字典。
我想出了这段代码:
def delete_book():
user_input = input('Input the name of the book to be deleted: ')
for book in books:
for key, value in book.items():
if book['name'] == user_input:
books.remove(book)
但它不起作用..我已经浏览了大约 2 小时以找到解决方案,作为初学者我无法弄清楚这一点,也许你们可以清除我的想法。
现在再看看字典中的键值read。我希望用户能够将值更改为 True。所以我尝试了很多版本,但这更难。这就是我所拥有的:
def mark_read(): # TODO REVIEW !!!!
book_name = input('Input name of the book: ')
for book in books:
if book == book_name:
user_input = input('Mark book as read? (y/N): ')
if user_input == 'N' or 'n':
print('No changes were made')
elif user_input == 'Y' or 'y':
book.update(read=True)
else:
print('The specified book is not currently in our database.')
那么你能告诉我我错在哪里,给我一个更好但更容易阅读的选项吗?
【问题讨论】:
-
Please don't add "solved" to your title or question。相反,mark an answer correct by clicking on the checkmark(你已经这样做了)。如果你收到的都没有解决你的问题,你也可以add your own answer接受。
标签: python list dictionary nested user-input