繁体   English   中英

字典中的元组列表——Python

[英]List of Tuples into a Dictionary -- Python

我有一个元组列表,我已将它们转换为字典,但我希望值是“书名”作为键,值是“作者姓名”。 这是我的元组列表:

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)

我的 output:

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

正如你所看到的,我的理查德亚当斯的书允许其中一本书。 我知道它正在跳过第一个,但我不知道该怎么做才能修复它。

谢谢

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

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']}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM