Shelina
Shelina

Reputation: 103

Python Error: IndexError list index out of range

 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?

Upvotes: 1

Views: 1577

Answers (3)

Conor
Conor

Reputation: 461

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

Upvotes: 1

mrCarnivore
mrCarnivore

Reputation: 5078

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()

Upvotes: 1

Daniel
Daniel

Reputation: 42758

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

Upvotes: 3

Related Questions