Search code examples
pythonlistdictionarynesteduser-input

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


I have the initial code:

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
        }
    )

I need the user to be able to provide the title of the book, and if his input maches the name in books, remove the whole dictionary that book its referred to. I came up with this code:

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)

But it's not working.. I've browsed around 2 hours to find a solution and as a beginner I can't figure this out, maybe you guys can clear up my mind.

Now take another look at the key value read from the dictionary. I want the user to be able to change the value to True. So I tried many versions but this is even harder. This is what I have:

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

So could you please tell me where I am wrong give me a better yet noob-readable option?


Solution

  • Code for deleting:

    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]
    

    Code for marking as read:

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