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

问题描述 投票:0回答:3

我有初始代码:

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

那么你能告诉我哪里错了,给我一个更好但菜鸟可读的选项吗?

python list dictionary nested user-input
3个回答
1
投票

删除代码:

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

0
投票

您的代码的问题在于,当您只需要一个字段时,您正在循环字典(

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'}]

0
投票

以上答案都不起作用,我尝试了所有解决方案,但是当我打印我的字典时,没有任何内容被删除,请提供一个代码,通过获取用户的输入从字典中删除项目。那会有帮助的。但是上面的答案对我在某些方面有帮助,谢谢

© www.soinside.com 2019 - 2024. All rights reserved.