Reputation: 1
I'm new to python and trying to do the following:
Open a CSV file with 5 different values separated by comma.
I want to store the data in a dictionary which key will be row[0]
.
Suppose there are 4 rows so 4 primary keys, for each key I need to create another nested dictionary with 4 new keys, each key with the values of rows 1, 2, 3 and 4.
Let's say the CSV contains:
1,hi,1,2,3
2,yes,2,3,4
3,no,3,4,5
4,why,4,5,6
and I need to store:
dict={'1': { 'key2':hi,'key3':1,'key4':2,'key5':3}, '2':{ }, '3':{}, '4':{} }
This is the code I'm using
import csv
dict={}
reader = csv.reader(open('filename.csv', 'r'))
for row in reader:
key=row[0]
for key in dict:
dict[key]={}
dict[key][key2]=row[1]
dict[key][key3]=row[2]
dict[key][key4]=row[3]
dict[key][key5]=row[4]
What am I missing?
Upvotes: 0
Views: 732
Reputation: 66
Here is code that does what you are asking:
import csv
my_dictionary = {}
reader = csv.reader(open('filename.csv', 'r'))
for row in reader:
my_dictionary[row[0]] = {}
for index in range(1, len(row)):
my_dictionary[row[0]]['key' + str(index)] = row[index]
You should avoid naming a dictionary 'dict' because that is the name of the function that creates dictionary objects. Also, the variable 'key' gets overwritten by your iterator variable.
Upvotes: 0
Reputation: 15854
The reason your code doesn't work is because for each row
you are iterating over keys of an empty dictionary for key in dict
resulting in no actions being taken.
Instead, if you would like to insert {'key2': row[1], 'key3': row[2], 'key4': row[3], 'key5': row[4]}
to dict[row[0]]
try the following. Also, avoid using variables named after builtin types, i.e. list
, set
, all
, dict
.
import csv
output_dict = {}
with open('filename.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
output_dict[row[0]] = {'key%d' % (i + 1): row[i] for i in xrange(1, 5)}
Upvotes: 2