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.

  • 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. – Pi Marillion Apr 05 '14 at 04: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. – DSM Apr 05 '14 at 04: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)? – Blckknght Apr 05 '14 at 05:08

2 Answers2

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]
Chris Hagmann
  • 1,086
  • 8
  • 14
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

Tim Lind
  • 150
  • 1
  • 9
  • Sorry for the delay in replying. This sounds useful, but when I try this, I get a syntax error, like this: File "", line 5 print dictionary['Psychoanalysis'] ^ SyntaxError: invalid syntax – user3458145 Apr 06 '14 at 22:17
  • 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 Apr 07 '14 at 08:41
  • @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 Apr 07 '14 at 10:33
  • @ 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 Apr 07 '14 at 13:53
  • @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. – Tim Lind Apr 07 '14 at 16:47