1
 file = open(selection, 'r')
 dict = {}
 with open(selection, 'r') as f:
    for line in f:
        items = line.split()
        key, values = items[0], items[1:]
        dict[key] = values
 englishWord = dict.keys()
 spanishWord = dict.values()

Hello, I am working on a project where I have an file with spanish and english words. I am trying to take these words, and put them into a dictionary. The file looks like this:

library, la biblioteca
school, la escuela
restaurant, el restaurante
cinema, el cine
airport, el aeropuerto
museum, el museo
park, el parque
university, la universidad
office, la oficina
house, la casa

Every time I run the code, I get an error about the range. What am I doing wrong?

2
  • How do you think the string 'library, la biblioteca' will be split? Commented Nov 9, 2017 at 17:42
  • You should give split() an explicit argument. In this case "," seems like the correct choice. Commented Nov 9, 2017 at 17:50

3 Answers 3

3

You probably have empty lines in your file, resulting in empty items-list:

dict = {}
with open(selection, 'r') as lines:
    for line in lines:
        items = line.split()
        if items:
            key, values = items[0], items[1:]
            dict[key] = values
Sign up to request clarification or add additional context in comments.

Comments

1

You do not need to open the file first if you need with! Also you need to specify what the character used for splitting needs to be, otherwise it splits on every whitespace and not on ',' as you want it to. This code works (assuming your file is called 'file.txt'):

dict = {}
with open('file.txt', 'r') as f:
    for line in f:
        items = line.split(',')
        print(items)
        key, values = items[0], items[1:]
        dict[key] = values
englishWord = dict.keys()
spanishWord = dict.values()

Comments

1

Check to make sure you don't have empty lines.

dict = {}
with open(selection, 'r') as lines:
    for line in lines:
        items = line.split()
        if (len(items) > 1):
            if items:
                key, values = items[0], items[1:]
                dict[key] = values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.