【问题标题】:List of Tuples into a Dictionary -- Python字典中的元组列表——Python
【发布时间】: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


【解决方案1】:

一种解决方案是将列表作为字典的值。因此,您可以将模式书名与作者关联:

books = [
    ("Douglas Adams", "The Hitchhiker"),
    ("Richard Adams", "Watership"),
    ("Richard Adams", "ship"),
    ("Mitch Albom", "The Five People"),
    ("Laurie Anderson", "Speak"),
    ("Maya Angelou", "Caged Bird Sings"),
]

out = {}
for author, title in books:
    out.setdefault(author, []).append(title)

print(out)

打印:

{'Douglas Adams': ['The Hitchhiker'], 'Richard Adams': ['Watership', 'ship'], 'Mitch Albom': ['The Five People'], 'Laurie Anderson': ['Speak'], 'Maya Angelou': ['Caged Bird Sings']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多