简体   繁体   中英

List of Tuples into a Dictionary -- Python

I have a list of tuples and I have converted them into a dictionary, but I would like to have the value be the "book name" be the key and the value be the "author name". this is my list of tuples:

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

How I converted it to a dictionary:

oneOfEachBook = dict(books) 
print(oneOfEachBook)

my output:

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

as you can see my books by Richard Adams are allowing one of the books. I understand that it is skipping the first but I do not know what to do to fix it.

Thanks

One solution is to have lists as values of the dictionary. Therefore you can have mode book names associated with the author:

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)

Prints:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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