【问题标题】:Map elements of a list as value of another dictionary将列表的元素映射为另一个字典的值
【发布时间】:2021-12-29 08:55:55
【问题描述】:

我想将列表的元素映射为字典的值(在列表中)。

字典列表:

sample_list = [{'url': 'http://www.ohmynews.com/NWS_Web', 'title': ‘japan returns letter to sk politicians’}, {'url': 'https://www.ytn.co.kr/_ln/0101_201812261600067045', 'title': ‘sk lawmakers return letters’}, {'url': 'http://www.seoul.co.kr/news', 'title': ‘island opens up to the public’}]

列表:

source_list = ['ohmynews', 'YTN', 'SeoulNews']

我想将source_list 的元素映射为'source' 中每个字典的键值sample_list

想要的输出:

output_list = [{'url': 'http://www.ohmynews.com/NWS_Web', 'title': ‘japan returns letter to sk politicians’, 'source':'ohmynews'}, {'url': 'https://www.ytn.co.kr/_ln/0101_201812261600067045', 'title': ‘sk lawmakers return letters’, 'source':'YTN'}, {'url': 'http://www.seoul.co.kr/news', 'title': ‘island opens up to the public’, 'source':'SeoulNews'}]

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    您可以使用列表推导。

    [d | {'source': source} for (d, source) in zip(sample_list, source_list)]
    

    我使用了以下组合:

    【讨论】:

    • 这很神奇,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 2021-07-16
    • 2019-05-17
    • 2021-12-11
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多