Search code examples
pythondictionarydata-sciencedata-analysis

How can I split my dictionary by the word 'by' and keep only the book name?


Here is a sample of my dictionary:

{'Fiction Books 2019': ['The Testaments by Margaret Atwood',
'Normal People by Sally Rooney',
'Where the Forest Meets the Stars by Glendy Vanderah',
'Ask Again, Yes by Mary Beth Keane',
'Queenie by Candice Carty-Williams',
"On Earth We're Briefly Gorgeous by Ocean Vuong",
'A Woman Is No Man by Etaf Rum',
'The Overdue Life of Amy Byler by Kelly Harms'... etc } 

How can I do to only keep the Name of the books?

I have tried the following but the loop adds all the books to every key in my dictionary:

books_name_dict = dict.fromkeys((col_names), [])

for k in books_name_dict:
    for i in range(len(nominee_list_dict_try[k])):
        books_name_dict[k].append(nominee_list_dict_try[k][i].split(' by ')[0])

Solution

  • You can use:

    books = {k: [x.split(" by ")[0] for x in v] for k, v in books.items()}
    

    Demo