ps0604
ps0604

Reputation: 1071

Restructure lists into dict

Given the following arrays:

fields1 = [ 'A1', 'B1', 'C1']
fields2 = [ 'A2', 'B2', 'C2']
array = [fields1, fields2, ...., fieldsN]

I need to reorganize the data programmatically into the following object:

the_fields = {
       'column1' : ['A1', 'A2'],
       'column2' : ['B1', 'B2'],
       'column3' : ['C1', 'C2']}

How can this be achieved?

Upvotes: 0

Views: 70

Answers (1)

cs95
cs95

Reputation: 402844

Option 1
zip
Use zipped packing inside a dict comprehension.

fields = [fields1, fields2, ...., fieldsN]
{'column{}'.format(i) : list(v) for i, v in enumerate(zip(*fields), 1)}

{
   'column1' : ['A1', 'A2'],
   'column2' : ['B1', 'B2'],
   'column3' : ['C1', 'C2']   
}

Option 2
pd.DataFrame.to_dict
This option uses the pandas API

import pandas as pd

pd.DataFrame(fields).rename(
    columns=lambda x: 'column{}'.format(x + 1)
).to_dict(orient='list')

{
   'column1' : ['A1', 'A2'],
   'column2' : ['B1', 'B2'],
   'column3' : ['C1', 'C2']   
}

Upvotes: 5

Related Questions