How to make two dict into one dict?

Issue

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'}]

Solution

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'}]

Answered By – I'mahdi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published