How do I convert a csv file with one column to a dictionary in Python?

Viewed 1052

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.

5 Answers

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'}

This should work for the given input:

data.csv:

1.male Bob West,
2.female Hannah South,
3.male Bruce North,

Code:

import csv

reader = csv.reader(open("data.csv"))

d = {}

for row in reader:
  splitted = row[0].split('.')
  # print splitted[0]
  # print ' '.join(splitted[1].split(' ')[1:])
  d[splitted[0]] = ' '.join(splitted[1].split(' ')[1:])

print(d)

Output

{'1': 'Bob West', '3': 'Bruce North', '2': 'Hannah South'}

as per Simit, but using regular expressions and realising that your 1. and A and B are you just trying to explain Excel cell and column identifiers

import re, csv

reader = csv.reader(open("data.csv"))

out = {}
for i, line in enumerate(reader, 1):
    m = re.match(r'^(male|female) (.*)$', line)
    if not m:
        print(f"error processing {repr(line)}")
        continue
    out[i] = m[2]

print(out)

I like to use Pandas for stuff like this. You can use Pandas to import it and then export it to a dict.

import pandas as pd

df = pd.read_csv('test.csv',header=-1)
# Creates new columns in the dataframe based on the rules of the question
df['Name']=df[0].str.split(' ',1).str.get(1)
df['ID'] = df[0].str.split('.',1).str.get(0)

The dataframe should have three columns:

  • 0 - This is the raw data.
  • Name - The name as defined in the problem.
  • ID - The number that comes before the period.

I didn't include gender, but it really won't fit into the dict. I'm also assuming your data does not have a header.

The next part converts your pandas dataframe to a dict in the output that you want.

output_dict = dict()
for i in range(len(df[['ID','Name']])):
    output_dict[df.iloc[i]['ID']] = df.iloc[i]['Name']
import cv with open('Employee_address.txt', mode='r') as CSV_file:
    csv_reader= csv.DirectReader(csv_file)
    life_count=0
    for row in csv_reader:
        if line_count==0:
            print(f'columns names are {",".join()}')
            line += 1
            print(f'\t{row["name"]} works in the {row["department"]} department, and lives in{row["living address"]}.line_count +=1 print(f'Processed {line_count} lines.')
Related