简体   繁体   English

使用for循环将两个列表组合成字典

[英]Combining two lists into dictionary using a for loop

I have two lists:我有两个列表:

headers = [Header1, Header2, Header3]
data = [(1, 'Name1'), (2, 'Name2'), (3, 'Name3'))]

I need to combine the lists into a dictionary into the format:我需要将列表组合成字典,格式如下:

database = {Header1 : [1, 2, 3], Header2 : ['Name1', 'Name2', 'Name3']}

I've tried using a nested for loop to no success, how would I achieve this?我试过使用嵌套的 for 循环但没有成功,我该如何实现呢?

You can use a dict comprehension with enumerate .您可以将字典理解与enumerate结合使用。

headers = ['Header1', 'Header2', 'Header3']
data = [(1, 'Name1'), (2, 'Name2'), (3, 'Name3')]
res = {header : [x[i] for x in data] for i, header in enumerate(headers) if i < len(data[0])}

You can use zip to pull out the values and then zip with the headers:您可以使用zip提取值,然后使用标题 zip:

headers = ['Header1', 'Header2', 'Header3']
data = [(1, 'Name1'), (2, 'Name2'), (3, 'Name3')]

dict(zip(headers, map(list, zip(*data))))

# {'Header1': [1, 2, 3], 'Header2': ['Name1', 'Name2', 'Name3']}

This explicitly creates lists;这明确地创建了列表; if you are okay with tuples, it's simpler:如果你对元组没问题,那就更简单了:

dict(zip(headers, zip(*data)))
# {'Header1': (1, 2, 3), 'Header2': ('Name1', 'Name2', 'Name3')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM