Bria
Bria

Reputation: 41

How do I convert nested list to dictionary?

I am currently working on an assignment where I need to convert a nested list to a dictionary, where i have to separate the codes from the nested list below.

data = [['ABC', "Tel", "12/07/2017", 1.5, 1000],['ACE', "S&P", "12/08/2017", 3.2, 2000],['AEB', "ENG", "04/03/2017", 1.4, 3000]] 

to get this

Code    Name    Purchase Date   Price   Volume
ABC     Tel     12/07/2017      1.5     1000
ACE     S&P     12/08/2017      3.2     2000
AEB     ENG     04/03/2017      1.4     3000

so the remaining values are still in a list, but tagged to codes as keys.

Could anyone advice on this please,thank you!

Upvotes: 4

Views: 2317

Answers (3)

DavidDr90
DavidDr90

Reputation: 569

You can use pandas dataframe for that:

import pandas as pd
data = [['ABC', "Tel", "12/07/2017", 1.5, 1000],['ACE', "S&P", "12/08/2017", 3.2, 2000],['AEB', "ENG", "04/03/2017", 1.4, 3000]] 

columns = ["Code","Name","Purchase Date","Price","Volume"]
df = pd.DataFrame(data, columns=columns)
print(df)

Upvotes: 2

Mykola Zotko
Mykola Zotko

Reputation: 17804

You can use a dictcomp:

keys = ['Code','Name','Purchase Date','Price','Volume']

{k: v for k, *v in zip(keys, *data)}

Result:

{'Code': ['ABC', 'ACE', 'AEB'],
 'Name': ['Tel', 'S&P', 'ENG'],
 'Purchase Date': ['12/07/2017', '12/08/2017', '04/03/2017'],
 'Price': [1.5, 3.2, 1.4],
 'Volume': [1000, 2000, 3000]}

Upvotes: 2

rovyko
rovyko

Reputation: 4577

I assume that by dictionaries you mean a list of dictionaries, each representing a row with the header as its keys.

You can do that like this:

keys = ['Code','Name','Purchase Date','Price','Volume']
dictionaries = [ dict(zip(keys,row)) for row in data ]

Upvotes: 1

Related Questions