Convert text file to dictionary


#1

I have a text file looks like this:
to search:mirar,buscar
to play:jugar
to be:ser,estar
to run:correr
to make:hacer
to talk:hablar
to take:tomar
to study:estudiar
to arrive:llegar
to practice:practicar

I want to convert it as a dictionary in python would looks like this (which the left of the colon is the key, and the right of the colon is the value):
dictionary={“to search”:“mirar,buscar”, “to play”:“jugar”…}

Someone could help me please? Thank you!


#2

what code do you have so far? What specifically do you need help with? Python has all the functionality to achieve this


#3
#choose a file to quiz English-Spanish verbs

file=raw_input("Choose one file for quiz: ")
while file=="verbs.txt":
    num=raw_input("10 entries found. How many words would you like to be quizzed on? ")
    print "Words: " +num
    break
else:
    print "Wrong file"

#convert verbs.txt to dictionary structure
   
import pandas as pd

data = pd.read_csv('lab6_verbs.txt', sep=":|,", header=None)

#4

That is the code I have so far, I have made the .txt as a data frame. The next step should change the dataframe to a dictionary: the 1st column is the key, 2nd and 3rd columns is the value. How to continue?


#5

Adding a key-value pair to a dict is straight-forward isn’t it? What are you missing to do that


#6

Do you have to use pandas? Its perfectly possible to achieve this without pandas

for the first entry:

to search:mirar,buscar

why separate mirar and buscar? if i look at your desired output:

dictionary={“to search”:“mirar,buscar”

you don’t separate these values, so why make a third column? Doesn’t seem you need it

yea, now looking over the data rows and adding to dictionary should be straight forward


#7

Yeah, pandas, dicts, files
What are you really asking about? Leave the other two out of it


#8

if for whatever reason you have data in file, from file to dictionary can make sense. Or from file to data frame also make sense

but from file to data frame to dictionary is a step too many


#9

https://www.google.com/search?q=pandas+dataframe+to+dict