gdm
gdm

Reputation: 71

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

Upvotes: 0

Views: 50

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195613

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

Upvotes: 3

Related Questions