我怎么能把字典按“by”一词分开,只保留书名呢?

2024-05-15 02:55:59 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的字典示例:

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

我怎么才能只保留书的名字呢

我尝试了以下方法,但循环会将所有书籍添加到字典中的每个键:

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])

Tags: thenamein示例forby字典books
3条回答

这是因为在对dict.fromkeys的调用中提供了单个列表实例[]。这就是为什么你会在每个列表中看到所有内容,实际上它只是一个列表

您应该能够通过使用defaultdict为每个键创建一个新的list来进行修复

import collections

books_name_dict = collections.defaultdict(list)
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])

更新

另一方面,可以更直接地完成迭代

for k, v in books_name_dict.items():
    for title in v:
        books_name_dict[k].append(title.split(' by ')[0])
books_name_dict = {'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']} 

for k,v in books_name_dict.items():
    books_name_dict[k] = [b.split(" by ")[0] for b in v]

您可以使用:

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

Demo

相关问题 更多 >

    热门问题