2

my goal is to create a dictionary in Python. I have a .csv file which contains two columns, first one being 'word', other being 'meaning'. I am trying to read the csv file in the dictionary format and get the 'meaning' when 'word' is given.

Can you please help me by telling me how to get the value of 'word'? this is what I tried:

My codes are,

>>> with open('wordlist.csv', mode = 'r') as infile:
...     reader = csv.reader(infile)
...     with open('wordlist.csv', mode = 'w') as outfile:
...         writer = csv.writer(outfile)
...         mydict = {rows[0]:rows[1] for rows in reader}
...     print(mydict)
...

The result turns out to be,

{}

the next one I tried was,

>>> reader = csv.reader(open('wordlist.csv', 'r'))
>>> d = {}
>>> for row in reader:
...     k, v = row
...     d[k] = v
... 

But when I wanted to use this, the result was like this-

>>> d['Try']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Try'

The next code I tried was,

>>> reader = csv.DictReader(open('wordlist.csv'))
>>> result = {}
>>> for row in reader:
...     key = row.pop('word')
...     if key in result:
...         pass
...     result[key] = row
...     print result
...

It didn't give me any answer at all.

>>> for row in reader:
...     for column, value in row.iteritems():
...         result.setdefault(column, []).append(value)
...     print result
... 

Neither did this give me a result.

3
  • Does the CSV file have header row at the top? How many? If possible, please provide a few example lines from the top of the CSV file you're trying to read. That should help us see why it's not working. Commented Apr 5, 2014 at 4:51
  • 2
    Your first code seems to open final_word.csv for reading and then opens it again for writing, which will clear the contents of the file. That doesn't seem like it's what you want. Commented Apr 5, 2014 at 4:53
  • Indeed, in light of the issue DSM points out, I suspect that the file was empty in your later tests! I hope you have a backup copy available. The later versions of your code may or may not work, depending on exactly what the contents of your file is. For instance, is there a header row? Do you have duplicate word values (and if so, how do you want to handle them)? Commented Apr 5, 2014 at 5:08

2 Answers 2

1

I would use pandas. You could then use zip two create the dictionaries.

import pandas as pd    

df = pd.read_csv('wordlist.csv')
words = list(df.word)
meaning = dict( zip( df.word, df.meaning ) )

if your file doesn't have a header row, that is ok. just print out the each column is still given some name which can then be referenced.

Alternative:

import pandas as pd    

df = pd.read_csv('wordlist.csv')
dictionary = {}

for w, s, m, p in zip(df.words, df.meaning):
    dictionary[w] = [m, p]
Sign up to request clarification or add additional context in comments.

Comments

1

If "final_word.csv" looks like this:

word1, synonym1, meaning1, POS_tag1
word2, synonym2, meaning2, POS_tag2

This will read it in as a dictionary:

with open("final_word.csv",'r') as f:
    rows = f.readlines()

dictionary = {}
for row in rows:
    row = row.strip()
    word, synonym, meaning, POS_tag = row.split(", ")
    dictionary[word] = [synonym, meaning, POS_tag]

print(dictionary['word1'])
#out>> ['synonym1', 'meaning1', 'POS_tag1']
print(dictionary['word2'][0])
#out>> synonym2

The strip() is used to get rid of the newlines "\n" that's in the end of each csv-row

5 Comments

Sorry for the delay in replying. This sounds useful, but when I try this, I get a syntax error, like this: File "<stdin>", line 5 print dictionary['Psychoanalysis'] ^ SyntaxError: invalid syntax
Thanks. I have Python 2.7. I have to use print as a statement. But when I try this ' Print dictionary['Psychoanalysis']'I am not getting the needed result. What might be the proper syntax?
@user3458145, I'd recommend you to use the parenthesises like this: print(dictionary['Psychoanalysis']) since it works in both py2.7 and py3.4. However, the syntax in py2.7 is: print dictionary['Psychoanalysis']
@ Tim Lind now it's giving me keyerror. I have the word in my ccorpus, and it shouldn't give me a keyerror. Any idea why?
@user3458145, well of some reason your word does not seem to exist as a key in the dictionary. Either it's not in the first column of the ccorpus-file, or you've misspelled the word. Dictionaries are case-sensitive, so that might be a thing to look into.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.