【问题标题】:Delete a dict from a list based on one value provided by user input - python根据用户输入提供的一个值从列表中删除一个字典 - python
【发布时间】: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.')

那么你能告诉我我错在哪里,给我一个更好但更容易阅读的选项吗?

【问题讨论】:

标签: python list dictionary nested user-input


【解决方案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.')

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-11-06
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      相关资源
      最近更新 更多