Seven Mathew
Seven Mathew

Reputation: 33

Convert csv to list of dictionaries of array

I have a csv file which is in the format

id1, atr1, atr2.... atrn
id2, atr2_1,atr2_2....atr2_n
.
.
idn, atrn_1,atrn_2....atrn_n

I need to convert it to list(dict(array)), for example

'id1': array([atr1, atr2.... atrn]),'id2': array([atr2_1,atr2_2....atr2_n])}]

Please help.

Upvotes: 0

Views: 88

Answers (2)

Corentin Pane
Corentin Pane

Reputation: 4943

Assuming you don't have meaningful spaces in the values you are trying to read, you can do the following:

with open("path//to//file", 'r') as f:
    result = {l[0] : l[1:] for l in (d.replace("\n", "").replace(" ", "").split(",") for d in f)}

This code parses each line, removes end of lines and spaces, and builds a dictionary using dictionary comprehension.

Upvotes: 0

Syed Jafer
Syed Jafer

Reputation: 306

You can read the csv file in python using the csv module . It will read each line as a list so u will be able to attain your need .

import csv 
res_dict = {}
with open(<file name>) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        key_ = row[0]
        values_ = row[1:]
        res_dict[key] = value

print(res_dict) 

Upvotes: 2

Related Questions