thclpr
thclpr

Reputation: 5938

Dictionary seems ok , but function returns "List index out of range"

I'm not sure why this function is returning "List index out of range" Since it seens ok. What the function does is basically work the content of the file.txt to create a dictionary with the values.

Resuming, the function will transform the content of the file.txt:

access_1;test_group_1,test_group_2

to:

[{'groups': 'test_group_1,test_group_2\n', 'acl': 'access_1'}

The current code:

def prepare_list():
    try:
        input_list = []
        ins = open("file.txt", "r")
        for line in ins:
            values = dict()
            values['acl'] = line.split(";")[0]
            values['groups'] = line.split(";")[1]
            input_list.append(values)
    except Exception, e:
        print "Error : %s" % e
    finally:
        return input_list

Output:

Error : list index out of range

Process finished with exit code 0

I'm running the script on the folder where the file exists.

Upvotes: 1

Views: 250

Answers (2)

thclpr
thclpr

Reputation: 5938

Based on the answer given by thefourtheye I was able to solve the problem testing if the file have lines with ; and striping new lines:

I could use the following correction:

def prepare_list():
    try:
        input_list = []
        ins = open("file.txt", "r")
        for line in ins:
        if line.strip() and ';' in line:
            values = dict()
            values['acl'] = line.split(";")[0]
            values['groups'] = line.split(";")[1]
            input_list.append(values)
            print "Correct : ",line
        else:
            print "line not correct. please fix it : ", line
            return False
    except Exception, e:
        print "Error : %s" % e

But it would print " line not correct, please fix it " for each new line, example with file with 4 new lines:

line not correct
line not correct
line not correct
line not correct

So, using the following i can remove the new lines, and clean the output to just show what is really wrong:

file content:

access_1;test_group_1,test_group_2
access_2test_group_1,test_group_2
<new line>
<new line>
<new line>
<new line>

function:

def prepare_list():
    try:
        input_list = []
        ins = open("file.txt", "r")
        for line in ins:
            # go away new lines, GO AWAY
            if line.strip()
                # test for valid char in line
                if ';' in line:
                    values = dict()
                    values['acl'] = line.split(";")[0]
                    values['groups'] = line.split(";")[1]
                    input_list.append(values)
                    print "Correct : ",line
                else:
                    print "line not correct. please fix it : ", line
    except Exception, e:
        print "Error : %s" % e

output:

Correct   : access_1;test_group_1,test_group_2
line not correct. please fix it : access_2test_group_1,test_group_2

Thanks for the help thefourtheye :)

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239493

data = "a;b"
print data.split(";")     # Prints ['a', 'b']
data = "ab"
print data.split(";")     # Prints ['ab']
print data.split(";")[1]  # raises IndexError: list index out of range

So, if ; is not there, it will return only one element. And if you try to access the second element, it will fail with that error.

If you know for sure that, all lines will have ; in them, your whole program can be written like this

keys = ("acl", "groups")
with open("Input.txt", "r") as ins:
    input_list = [{k:v for k, v in zip(keys,l.rstrip().split(";"))} for l in ins]
print input_list

Upvotes: 2

Related Questions