首页 > 解决方案 > 将 2 个相同大小的列表合并到一个 dicts Python 列表中

问题描述

我有两个相同大小的列表:

['/phoenix', '/scottsdale', '/tempe']
['Phoenix', 'Scottsdale', 'Tempe']

如何将它们组合到一个字典列表中:

[
    {'slug': '/phoenix', 'title': 'Phoenix'},
    {'slug': '/scottsdale', 'title': 'Scottsdale'},
    {'slug': '/tempe', 'title': 'Tempe'}
]

标签: pythonpython-3.x

解决方案


您可以使用:

l1 = ['/phoenix', '/scottsdale', '/tempe']
l2 = ['Phoenix', 'Scottsdale', 'Tempe']
print([{'slug': a, 'title': b} for (a, b) in zip(l1, l2)])

输出:

[{'slug': '/phoenix', 'title': 'Phoenix'},
 {'slug': '/scottsdale', 'title': 'Scottsdale'},
 {'slug': '/tempe', 'title': 'Tempe'}]

推荐阅读