I want to make title and image dict data to one dict:
#From this:
title = [{"title":"Title Text One"},{"title":"Title Text Two"},{"title":"Title Text Three"}]
image = [{"image": "happy.jpg"}, {"image": "smile.jpg"}, {"image": "angry.jpg"}]
#To this:
data = [{"title": "Title Text One", "image": "happy.jpg"},{"title":"Title Text Two", "image": "smile.jpg"}, {"title":"Title Text Three", "image": "angry.jpg"}];
CodePudding user response:
You can try this, If your two array of dict have same length:
>>> title = [{"title":"Title Text One"},{"title":"Title Text Two"},{"title":"Title Text Three"}]
>>> image = [{"image": "happy.jpg"}, {"image": "smile.jpg"}, {"image": "angry.jpg"}]
>>> [{**title[i], **image[i]} for i in range(len(title))]
[{'image': 'happy.jpg', 'title': 'Title Text One'},
{'image': 'smile.jpg', 'title': 'Title Text Two'},
{'image': 'angry.jpg', 'title': 'Title Text Three'}]
CodePudding user response:
title = [{"title":"Title Text One"},{"title":"Title Text Two"},{"title":"Title Text Three"}]
image = [{"image": "happy.jpg"}, {"image": "smile.jpg"}, {"image": "angry.jpg"}]
data = image
[data[i].update(title[i]) for i in range(len(title))]
data
Output:
[{'image': 'happy.jpg', 'title': 'Title Text One'},
{'image': 'smile.jpg', 'title': 'Title Text Two'},
{'image': 'angry.jpg', 'title': 'Title Text Three'}]