我想將串列的元素映射為字典的值(在串列中)。
字典串列:
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'}]
uj5u.com熱心網友回復:
您可以使用串列理解。
[d | {'source': source} for (d, source) in zip(sample_list, source_list)]
我使用了以下組合:
- zip 將串列組合成一個可迭代物件
|運算子合并字典(Python 3.9)。請參閱PEP 584 -- 將聯合運算子添加到 dict
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398310.html
