Dan_24
Dan_24

Reputation: 25

Appending a list to a dictionary

I'm trying to read a text file separated by kewords. I'm using a dictionary to organize the information corresponding to each section. For example, for the text file:

*VERTICES
1 0 0
2 10 0
3 10 10
4 0 10
*EDGES
1 1 2
2 1 4
3 2 3
4 3 4

has the *EDGES and *VERTICES sections. My goal is to produce a dictionary like:

dict = {'*VERTICES': [[0,0], [0,10], [10,0], [10,10]], '*EDGES': [[1,2], [1,4], [2,3], [3,4]]}

This is my code:

with open('c:/geometry.txt','r') as inputfile:
    xyz = []
    dic = {}
    key = None
    for line in inputfile:
        line = line.replace(',','')
        linelist = ' '.join(line.split())
        linelist = linelist.split(' ')
        if(linelist[0][0]=='*'):
            key = linelist[0]
            dic[key] = []
        else:
            for i in range(0,len(linelist)):
                string2float = float(linelist[i])
                xyz.append(string2float)
            dic[key].append(xyz)
            del xyz[:]

print(dic)

And this is the current output:

{'*VERTICES': [[], [], [], []], '*EDGES': [[], [], [], []]}

Emtpy, as you can see. I'm guessing that the erros is at the dic[key].append(xyz) line. What I'm I doing wrong? I noticed that if I try to append linelist instead (e.g. dic[key].append(linelist)), the code works fine, but I wont have my variables transformed from string to float.

Is there any way I can get it to work with the xyz (float) list? Thanks

Upvotes: 1

Views: 146

Answers (2)

pzp
pzp

Reputation: 6607

It looks like you're greatly overcomplicating this. Your code is very difficult to follow, due partly to cryptic variable names (what is xyz?). @Blckknght correctly identified the cause of the bug in your program. (In fact, I gave him/her an upvote.) The only thing I can contribute here is some working code:

d = {}

with open('c:/geometry.txt','r') as f:
    for line in f:
        if line.startswith('*'):
            key = line.strip()
            d[key] = []
        else:
            d[key].append(map(int, line.split()[1:]))

Upvotes: 0

Blckknght
Blckknght

Reputation: 104762

The very last lines of your code are not doing what you want them to do:

        dic[key].append(xyz)
        del xyz[:]

You're appending a reference to your xyz list to the list in the dictionary, but they you're delting the list's contents. The del statement on the slice modifies the list in place, so the references stored in the dictionary will also see the empty list result afterwards.

In fact, all your empty inner lists in the dictionary are references to the same empty xyz list. What you probably want to do is to actually create a new list for xyz, rather than deleting its contents:

        dic[key].append(xyz)
        xyz = []

Or, better yet, use a list comprehension to build the new list with its contents and get rid of the xyz variable entirely:

    else:
        dic[key].append([float(num) for num in linelist])

Note that this will include all three values from your file in the inner dictionaries. If you only want two, you probably want to slice linelist.

Upvotes: 1

Related Questions