从字典中追加到列表?

时间:2019-03-31 17:03:57

标签: python list dictionary

尝试将作者及其书名添加到词典中的列表中,以便每个作者可以支持多个书名。在代码中,我已经有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')

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

2 个答案:

答案 0 :(得分:0)

您的工作流程有点差。在检查了作者之后,然后在该作者的书籍列表中检查书籍。您可以使用.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}"')

答案 1 :(得分:0)

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

readings[author].append(bookTitle)

代替

readings[author] = bookTitle
相关问题