I want to map elements of a list as a value of a dictionary (in a list).
A list of dictionaries:
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’}]
A list:
source_list = ['ohmynews', 'YTN', 'SeoulNews']
I want to map elements of the source_list
as a value of key 'source'
for each dictionary in sample_list
Wanted output:
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'}]
CodePudding user response:
You can use a list comprehension.
[d | {'source': source} for (d, source) in zip(sample_list, source_list)]
I used a combination of:
- zip to combine lists into one iterable
|
operator to merge dictionaries (Python 3.9). See PEP 584 -- Add Union Operators To dict