Home > Blockchain >  Map elements of a list as value of another dictionary
Map elements of a list as value of another dictionary

Time:12-29

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:

  • Related