0

I need to create a dictionary from an Excel file.

Excel sheet (2r: nearly 3000 columns) looks like this:

enter image description here

And I want my outcome to look like this:

dictionary ={ 
              "aa": "male", 
              "ab": "female",
              ...,
              "name_N": "gender_N"
              }

I wrote my code as follows, however, it does not work.

import csv

dictionary = {}
with open('genderword_sk2.csv', 'r') as f:
    reader = csv.DictReader(f)
for row in reader:
    dictionary[row['name']] = row['gender']
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
jhj776
  • 19
  • What exactly do you mean by "it does not work"? – mkrieger1 Jul 08 '20 at 20:22
  • Is this [here](https://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file) what you are looking for? – Kel Varnsen Jul 08 '20 at 20:23
  • @mkrieger1 this is an error message I've got --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in 5 reader = csv.DictReader(f) 6 for row in reader: ----> 7 dictionary[row['name']] = row['gender'] KeyError: 'name' – jhj776 Jul 08 '20 at 20:27
  • Error traceback should be part of question. Did you read the error message? Did you try to debug? E.g., print the `row` variable before it crashes? – Mad Physicist Jul 08 '20 at 20:29
  • Also, you appear to be closing the file before you read it – Mad Physicist Jul 08 '20 at 20:30

2 Answers2

0
import csv

dictionary = {}

with open('genderword_sk2.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    next(csvreader)

    for row in csvreader:
        dictionary[row[0]] = row[1]

print(dictionary)

This was the content of my csv:

name,gender
Anne,female
Tom,male 

And the result was:

{'Anne': 'female', 'Tom': 'male'}
CCBet
  • 416
  • 1
  • 6
  • 19
0

One option is to use pandas.

import pandas as pd

df = pd.read_csv('genderword_sk2.csv')

dictionary = {df['name'].iloc[i] : df['gender'].iloc[i] for i in df.index}