根据用户输入提供的一个值从列表中删除字典 - python

Delete a dict from a list based on one value provided by user input - python

我有初始代码:

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.')

所以你能告诉我我错在哪里给我一个更好但新手可读的选项吗?

您的代码存在的问题是,当您只需要一个字段 (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'}]

删除代码:

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.')