【发布时间】:2021-04-15 20:02:55
【问题描述】:
我有一个元组列表,并将它们转换为字典,但我希望值是“书名”作为键,值是“作者姓名”。 这是我的元组列表:
books=[('Douglas Adams', "The Hitchhiker"), ('Richard Adams', 'Watership'),('Richard Adams', 'ship'), ('Mitch Albom', 'The Five People'), ('Laurie Anderson', 'Speak'), ('Maya Angelou', 'Caged Bird Sings')]
我如何将其转换为字典:
oneOfEachBook = dict(books)
print(oneOfEachBook)
我的输出:
{'Douglas Adams': 'The Hitchhiker', 'Richard Adams': 'ship', 'Mitch Albom': 'The Five People', 'Laurie Anderson': 'Speak', 'Maya Angelou': 'Caged Bird Sings'}
如您所见,我的理查德亚当斯的书允许其中一本书。我知道它正在跳过第一个,但我不知道如何修复它。
谢谢
【问题讨论】:
-
那是因为
dict不能有重复的键。尝试将每个作者的多本书存储在该作者的列表中/
标签: python list dictionary tuples