Reputation: 4766
I have my data following format in csv file and I want to convert this csv data into dictionary having the first attribute as the key and the rest as values
user115,1,4,8,6
user142,0,2,1,11
user145,0,0,0,3
user148,5,9,22,8
user151,2,7,8,8
Note: In my csv file there is no header line. I have to provide it explicitly.
I tried to convert it using CSV DictReader using following code segment but it is giving me error/ not providing the expected outcome
reader = csv.DictReader(open(file_name),'rb', fieldnames=('key','val1','val2','val3','val4'))
Gives me
TypeError: __init__() got multiple values for argument 'fieldnames'
What is the correct way to do this
Upvotes: 0
Views: 2367
Reputation: 3713
You can do that via pandas
import pandas as pd
d = pd.read_csv(file_name, header=None, index_col=0)
d.T.to_dict("list")
>>> {'user115': [1, 4, 8, 6],
'user142': [0, 2, 1, 11],
'user145': [0, 0, 0, 3],
'user148': [5, 9, 22, 8],
'user151': [2, 7, 8, 8]}
Upvotes: 2
Reputation: 580
You can use the csv
module and this code snippet
def csv_dict_list(path, fieldnames):
csv_dict_list = []
with open(path, 'r') as csv_file:
reader = csv.DictReader(csv_file, fieldnames = field_names)
for row in reader:
csv_dict_list.append(row)
return csv_dict_list
path = 'YOUR/PATH/HERE/file.csv'
The fieldnames
should be a list, like:
field_names = ['Column A', 'Column B', 'Column C', 'Column D', 'Column E']
And then you just call the method
newdict = {}
newdict = csv_dict_list(path, fieldnames)
Upvotes: 1
Reputation: 82765
Using csv module
.
Ex:
import csv
d = {}
with open(filename, "rU") as infile:
reader = csv.reader(infile)
for line in reader:
d[line[0]] = line[1:]
print(d)
Output:
{'user148': ['5', '9', '22', '8'], 'user142': ['0', '2', '1', '11'], 'user145': ['0', '0', '0', '3'], 'user151': ['2', '7', '8', '8'], 'user115': ['1', '4', '8', '6']}
Upvotes: 1