I need some help with a assignment for python. The task is to convert a .csv file to a dictionary, and do some changes. The problem is that the .csv file only got 1 column, but 3 rows.
The .csv file looks like this in excel
A B
1.male Bob West
2.female Hannah South
3.male Bruce North
So everything is in column A.
My code looks so far like this:
import csv
reader = csv.reader(open("filename.csv"))
d={}
for row in reader:
d[row[0]]=row[0:]
print(d)
And the output
{'\ufeffmale Bob West': ['\ufeffmale Bob West'], 'female Hannah South':
['female Hannah South'], 'male Bruce North': ['male Bruce North']}
but I want
{1 : Bob West, 2 : Hannah South, 3 : Bruce North}
The male/female should be changed with ID, (1,2,3). And i don´t know how to figure out the 1 column thing.
Thanks in advance.
You can use dict comprehension and enumerate the csv
object,
import csv
reader = csv.reader(open("filename.csv"))
x = {num+1:name[0].split(" ",1)[-1].rstrip() for (num, name) in enumerate(reader)}
print(x)
# output,
{1: 'Bob West', 2: 'Hannah South', 3: 'Bruce North'}
Or you can do it without using csv
module simply by reading the file,
with open("filename.csv", 'r') as t:
next(t) # skip first line
x = {num+1:name.split(" ",1)[-1].strip() for (num, name) in enumerate(t)}
print(x)
# output,
{1: 'Bob West', 2: 'Hannah South', 3: 'Bruce North'}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments