Home > other >  Transform a txt file to dictionary in Python
Transform a txt file to dictionary in Python

Time:03-12

Assuming a following text file (lemma_es.txt) is present:

comer coma
comer comais
comer comamos
comer coman

The first column represents the lemma of the second column and the second column represents the inflected word.

I am trying to make a dictionary in which the keys are the words in the second word and the values are the words in the first column.

The output I need:

{'coma': 'comer', 'comais': 'comer', 'comamos': 'comer', 'coman': 'comer' ... }

Thank you all!

CodePudding user response:

I think you could try this:

myfile = open("lemma_es.txt", 'r')
data_dict = {}
for line in myfile:
    k, v = line.strip().split()
    data_dict[k.strip()] = v.strip()
 
myfile.close()
 
print(' text file to dictionary =\n ',data_dict)

CodePudding user response:

word_dict={}
with open("lemma_es.txt","r") as filehandle:
    for line in filehandle.readlines():
        word_dict[line.split()[-1]]=line.split()[0]

Read the txt file and read each line using readlines . Split the line and Just use the second value of list as key.

CodePudding user response:

IIUC, you could use:

with open('lemma_es.txt') as f:
    d = dict(reversed(l.strip().split()) for l in f)

output:

{'coma': 'comer', 'comais': 'comer', 'comamos': 'comer', 'coman': 'comer'}

NB. note that the second words must be unique

  • Related