【发布时间】: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