2 回答

TA貢獻1833條經(jīng)驗 獲得超4個贊
刪除代碼:
def delete_book():
user_input = input('Input the name of the book to be deleted: ')
for i,book in enumerate(books):
if book['name'] == user_input:
del books[i]
標記為已讀的代碼:
def mark_read(): # TODO REVIEW !!!!
book_name = input('Input name of the book: ')
f=0 #flag to see if book is present in dict
for book in books:
if book['name'] == book_name:
f=1
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['read']=True
break #if book is found, you can exit the loop early
if f==0:
print('The specified book is not currently in our database.')

TA貢獻1802條經(jīng)驗 獲得超6個贊
您的代碼的問題在于,當您只需要一個字段 () 時,您正在循環(huán)字典name。因此,您正在刪除具有字典第一個字段的書,但您試圖再次刪除具有字典下一個字段的條目,這是不可能的。
您不需要遍歷字典的所有字段來只比較一個字段。以下作品:
books =[{'name': "Hello", "author": "Arthur"}, {'name': "Hi", "author": "Vicky"}]
user_input = input('Input the name of the book to be deleted: ')
for book in books:
if book['name'] == user_input:
books.remove(book)
print(books)
輸入“Hi”時的結果:
[{'name': 'Hello', 'author': 'Arthur'}]
添加回答
舉報