'Transform a txt file to dictionary in Python

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' ... }

Edit: The txt starts with:

1 primer
1 primera
1 primeras
1 primero

There are some words that's need to be duplicated, only in dictionary's values, first column of words in txt.

Thank you all!



Solution 1:[1]

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)

Solution 2:[2]

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.

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AirĂ£ Carvalho da Silva
Solution 2 Ajay Pyatha
Solution 3