pythonstudent
pythonstudent

Reputation: 39

Creating dictionaries from a text file

I have a text file which reads:

name,number,number,number
name,number,number,number
...

and I want to create a dictionary from it. I found this bit of code:

file = open('Results.txt', 'r')
lines = file.read().splitlines()
s = {lines[i]:[float(k) for k in lines[i+1:i+4]] for i in range(0,len(lines),4)}

However it only works for files with this format:

name
number
number
number
name
number
number
number
...

How can I make it work from my format? Also, is it possible to make it still work if there are less than 3 numbers after the name?

Upvotes: 1

Views: 113

Answers (1)

martineau
martineau

Reputation: 123393

The following will handle lines with one or more comma-separated numbers following a name on each line of the file:

with open('Results.txt') as file:
    s = {items[0]: [float(item) for item in items[1:]]
            for items in (line.split(',') for line in file)}

Upvotes: 1

Related Questions