Home > Software engineering >  Combining two lists into dictionary using a for loop
Combining two lists into dictionary using a for loop

Time:01-25

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?

CodePudding user response:

You can use a dict comprehension with 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])}

CodePudding user response:

You can use zip to pull out the values and then zip with the headers:

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')}
  • Related