如何把两个字典变成一个字典?



我想让标题和图像字典数据到一个字典:

从这个:

title = [{'title': 'Title Text One'},
{'title': 'Title Text Two'},
{'title': 'Title Text Three'}]
image = [{"image": "happy.jpg"},
{"image": "smile.jpg"},
{"image": "angry.jpg"}]

:

data = [{'title': 'Title Text One', 'image': 'happy.jpg'},
{'title': 'Title Text Two', 'image': 'smile.jpg'},
{'title': 'Title Text Three', 'image': 'angry.jpg'}]

你可以试试这个,如果你的两个字典数组长度相同:

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

输出:

[{'image': 'happy.jpg', 'title': 'Title Text One'},
{'image': 'smile.jpg', 'title': 'Title Text Two'},
{'image': 'angry.jpg', 'title': 'Title Text Three'}]

对于Python 3.9+:

out = [t | i for t, i in zip(title, image)]
print(out)

打印:

[
{"title": "Title Text One", "image": "happy.jpg"},
{"title": "Title Text Two", "image": "smile.jpg"},
{"title": "Title Text Three", "image": "angry.jpg"},
]

或:

out = [{**t, **i} for t, i in zip(title, image)]

相关内容

  • 没有找到相关文章

最新更新