【问题标题】:appending to a list from inside a dictionary?从字典中附加到列表?
【发布时间】:2019-04-01 01:12:33
【问题描述】:

尝试将作者及其书名添加到字典内的列表中,以便每个作者都可以支持多个书名。在代码中,我已经有 3 个作者,每个作者都有 1 个书名,但他们需要能够支持至少 1 个以上的书名。

我已经将键(作者)的值(书名)嵌套在字典内的列表中,但我不知道如何将更多值附加到现有列表中的现有键。

readings = {'George Orwell': ['1984'], 'Harper Lee': ['To Kill a Mockingbird'], 'Paul Tremblay': ['The Cabin at the End of the World']}  # list inside of dict.

我需要使用以下代码将新书名附加到列表中

def add(readings):  # appending to list will go here
    author = input('\nEnter an author: ')
    if author in readings:  # check if input already inside dict.
        bookTitle = readings[author]
        print(f'{bookTitle} is already added for this author.\n')
    else:
        bookTitle = input('Enter book title: ')
        bookTitle = bookTitle.title()
        readings[author] = bookTitle
        print(f'{bookTitle} was added.\n')

我希望您不能两次添加相同的书名,也不能两次添加同一作者。我希望能够在程序运行时为现有作者(或尚不存在的新作者)输入书名,然后能够通过“命令菜单”查看所有作者及其书名(未显示)。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    您的工作流程有点偏离。在检查作者之后,然后在该作者的书籍列表中检查书籍。您可以使用.append 向图书列表添加标题。试试这个:

    def add(readings):  # appending to list will go here
        author = input('\nEnter an author: ')
        if author in readings:  # check if input already inside dict.
            books = readings[author]
            print(f'Found {len(books)} books by {author}:')
            for b in books:
                print(f' - {b}')
        else:
            readings[author] = []
    
        bookTitle = input('Enter book title: ')
        bookTitle = bookTitle.title()
    
        if bookTitle in readings[author]:
            print(f'{bookTitle} is already added for this author.')
        else:
            readings[author].append(bookTitle)
            print(f'Add "{bookTitle}"')
    

    【讨论】:

      【解决方案2】:

      所以您正尝试向作者添加多本书,对吗?由于您的字典中的值已经存储为列表,您可以尝试这样做 -

      readings[author].append(bookTitle)
      

      而不是

      readings[author] = bookTitle
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-15
        • 2020-06-01
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        相关资源
        最近更新 更多