【问题标题】:How can I split my dictionary by the word 'by' and keep only the book name?如何按单词“by”拆分字典并仅保留书名?
【发布时间】:2020-04-14 02:11:47
【问题描述】:

这是我的字典示例:

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

【问题讨论】:

  • df['Fiction Books 2019'].str.split(" by ").str[0]?

标签: python dictionary data-science data-analysis


【解决方案1】:

你可以使用:

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

Demo

【讨论】:

  • 这很好用 - 谢谢!推出 Demo 是个好主意! ~~
【解决方案2】:

这是因为您在对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])

【讨论】:

  • 谢谢你,这也很好用!感谢您的意见!
【解决方案3】:
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]

【讨论】:

    猜你喜欢
    • 2014-11-28
    • 2011-05-22
    • 2023-01-31
    • 2020-03-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多