我想从books_brary中删除的书的示例(取决于书名(输入((:
"图书":[{"图书ID":{'01'},"图书名称":{‘复仇者’},《图书作者》:{‘斯坦·李’}、《图书出版年份》:{1938'}、"图书类型":{'1'},},"书名":{"蜘蛛侠"},"作者":{"李"},";图书出版年份":{1948’};书籍类型":{'2'},";书籍副本":{15}}]}
我正在使用的函数:
def delete_book(book_name, books_library):
"""
A function that update the collection of books that in the library, without deleting one.
:param book_name: The name of the book to delete.
:param books_library: A collection of all the books in library
"""
for book in range(len(books_library["Books"])):
if book_name in books_library["Books"][book]["Book's Name"]:
print("Are you sure you want delete this book?: ")
identifier = input()
identifiers = ['y','n']
while identifier not in identifiers:
print("Please answer with y or n")
print("Are you sure you want to delete this book?: ")
identifier = input()
if identifier == 'y':
books_library["Books"][book].pop(book)
return f"{book_name} is deleted from books library"
## Todo : Find a way to delete book by his name (should delete all books details)
else:
print(f"The book {book_name} does not exist!")
if identifier == 'n':
print("Canceling...")
break
我在Main.py中使用的代码:
if identifier == '4': # choosing to Remove a book
print("Which book would you like to remove?: n")
book_name = input()
delete_book(book_name, books_library)
print("The Book has deleted from library.")
我每次都会得到的错误:
Traceback (most recent call last):
File "d:John bryce - pythonFirstProject-managing book librarymain.py", line 83, in
<module>
delete_book(book_name, books_library)
File "d:John bryce - pythonFirstProject-managing book libraryLibraryBooks.py",
line 91, in delete_book
books_library["Books"][book].pop(book)
KeyError: 0
尝试替换:
books_library["Books"][book].pop(book)
签字人:
books_library["Books"].pop(book)
基于此:
{'Books': [{"Book's ID": {'001'}, "Book's Name": {'Avengers'}, "Book's Authors": {'Stan Lee'}, "Book's Published year": {'1938'}, "Book's Type": {'1'}, "Book's Copies": {'10'}}, {"Book's ID": {'002'}, "Book's Name": {'Spider Man'}, "Book's Authors": {'Stan Lee'}, "Book's Published year": {'1948'}, "Book's Type": {'2'}, "Book's Copies": {'15'}}]}
您正在从"Books_brary"字典中选择"Books"。
books_library=>dict
books_library['books']=>列出
books_library[quot;books"][book]=>dict
记住第一行
for book in range(len(books_library["Books"]))
"book"是一个整数,它不作为关键字出现在books_brary[quot;books"][book]下的dict中。
我认为这个词应该是
books_library['Books'].pop(book)