Andrejovic Andrej
Andrejovic Andrej

Reputation: 218

Creating a dict from CSV file

I have a csv file which looks like this

   header1   header2   header3
1  value1    value2    value3
2  value4    value5    
3            value6    value7

And I would like to make a dict which will look like this:

{header1:[value1, value4],
header2:[value2, value5, value6],
header3:[value3, value7]

}

I already tried

records = csv.DictReader(f)
    for row in records:
         print(row)

But It takes first column values as keys in dict what could I do?

Upvotes: 1

Views: 73

Answers (3)

Gaurav Agarwal
Gaurav Agarwal

Reputation: 611

You can use pandas for this.

import pandas as pd
df = pd.read_csv("Your CSV file name")
dict1 = df.to_dict('list')
print(dict1)

Upvotes: 0

Prince Francis
Prince Francis

Reputation: 3097

use pandas dataframe to read csv and convert to dict

import pandas as pd
df = pd.read_csv('test2.csv', sep=',')
df.to_dict('list')

It gives the below output.

{
'header1': ['value1', 'value4', nan],
 'header2': ['value2', 'value5    ', 'value6'],
 'header3': ['value3', nan, 'value7']
}

Upvotes: 0

tripleee
tripleee

Reputation: 189307

Here's one quick and I hope obvious way.

from csv import DictReader
from collections import defaultdict

result = defaultdict(list)
records = DictReader(f)
for row in records:
     for key in row:
         result[key].append(row[key])

Upvotes: 2

Related Questions