Rhs
Rhs

Reputation: 3318

How to read file into dictionary in python

I have a text file in the format of the following:

hsa04012 [[['7039', '1956', '1398', '25'], ['7039', '1956', '1399', '25']], [['1839', '1956', '1398', '25'], ['1839', '1956', '1399', '25']], [['1399', '25']], [['1398', '25']], [['727738', '1956', '1398', '25'], ['727738', '1956', '1399', '25']], [['1956', '1398', '25'], ['1956', '1399', '25']], [['1950', '1956', '1398', '25'], ['1950', '1956', '1399', '25']], [['374', '1956', '1398', '25'], ['374', '1956', '1399', '25']], [['2069', '1956', '1398', '25'], ['2069', '1956', '1399', '25']], [['685', '1956', '1398', '25'], ['685', '1956', '1399', '25']]]
hsa02331...

How can I read the file into a dictionary with the key as the text containing hsa... and the value as the numbers within the brackets [as a list].

Thanks in advance

Upvotes: 0

Views: 616

Answers (1)

mgilson
mgilson

Reputation: 310267

I'd use str.split and ast.literal_eval. That seems easiest...

with open(datafile) as f:
    d = {}
    for line in f:
        key,value = line.split(None,1)
        d[key] = ast.literal_eval(value)

Although, you might be able to play some games with json to get the lists as well. The lists look to be quite valid JSON arrays, as they are called.

Upvotes: 4

Related Questions