0
def read_wiktionary(file):

     infile=open(file,'r')       
     content=infile.readlines()   
     infile.close()               
     d = dict()                  
     for i in content:       
          d[i]=i[1]          

     return d

File is on notepad has about 30 lines. Each line has a word separated by a comma and then the number of occurrences the word appears in English language. I know i[1] is out of range but I cant figure our how to make it in range so this works. Help please.

File content:

a,1
be,2
see,3

Expected result:

{'a':'1', 'be':'2', 'see':'3'}
wwii
  • 23,232
  • 7
  • 37
  • 77
  • Possible duplicate - https://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file – Transhuman Sep 24 '17 at 01:09
  • Unfortunately SO isn't a study group, study forum or code writing service. – wwii Sep 24 '17 at 01:42
  • Please read [mcve]. It helps us if you provide a minimal example of the input and desired output. If you are asking a question about code that throws an error/exception, please post the complete Traceback. – wwii Sep 24 '17 at 01:49
  • Ok, sorry. I was just about to do that but someone just did it. Am new to SO. I tried liking or following you guys but don't know how. Will read up on it tommorrow. Burnt out. – Andy Calderon Sep 24 '17 at 02:39

1 Answers1

0

Have you tried splitting on the comma?

infile=open(file,'r')       
content=infile.readlines()   
infile.close()               
d = dict()                  
for i in content:
    assert len(i.split(',')) == 2
    a, b = i.split(',')
    d[a.strip()]=b.strip()
return d

Note that I am using an assert statement to confirm your statement about the file having two items separated by a comma. I'm also strip()ing the terms so they lack leading/trailing spaces/newlines.


Refactored:

with open(file) as infile:
    for line in infile:
        line = line.strip()
        key, value = line.split(',')
        d[key] = value
wwii
  • 23,232
  • 7
  • 37
  • 77
JacobIRR
  • 8,545
  • 8
  • 39
  • 68
  • That was the first thing that came to mind was to split by comma, however I did it wrong because got error message. I see what your saying as I was thinking the same just didn't know how to code it. I just tried this piece of code but the for loop is giving me a syntax error message, can't assign to function call. Will mess around with it. I don't know strip but will use help funtion to see explanation also. – Andy Calderon Sep 24 '17 at 01:41
  • Sorry, I forgot you can't call split() at the top of a loop. My change splits the string on the comma inside the loop body. – JacobIRR Sep 24 '17 at 01:45
  • Thanks! Refactored worked. I did the same split outside loop. this worked though. I'm just trying to figure out how to get the value output as a non string since it is a large number. Should be easy enough thanks. – Andy Calderon Sep 24 '17 at 02:26