当前位置: 动力学知识库 > 问答 > 编程问答 >

Python read an archive for a dictionary

问题描述:

How do I read a file and transform the information of the following line into a python dictionary:

file:

orig sorted(list(set(loadDB('db/path_orig'))))

dest sorted(list(set(loadDB('db/path_dest'))))

md_dest ''.join(loadDB('db/path_md_dest'))

main ''.join(loadDB('db/main_batch'))

copy ''.join(loadDB('db/copy_batch'))

expected outcome:

option = {

'orig': sorted(list(set(loadDB('db/path_orig')))),

'dest': sorted(list(set(loadDB('db/path_dest')))),

'md_dest': ''.join(loadDB('db/path_md_dest')),

'main': ''.join(loadDB('db/main_batch')),

'copy': ''.join(loadDB('db/copy_batch'))

}

I tried:

with open('text') as f:

d = dict(x.rstrip().split(None, 1) for x in f)

outcome:

d = {

'main': "''.join(loadDB('db/main_batch')),",

'copy': "''.join(loadDB('db/copy_batch'))",

'dest': "sorted(list(set(loadDB('db/path_dest')))),",

'md_dest': "''.join(loadDB('db/path_md_dest')),",

'orig': "sorted(list(set(loadDB('db/path_orig')))),"

}

网友答案:

Something like this?

import ast

with open('text','r') as f:
    d1 = {line.strip().split(' :: ')[0]:line.strip().split(' :: ')[1] for line in f}

d2={}
for k,v in d1.iteritems():
    d2[k] = ast.literal_eval(v)
网友答案:

This is a bit of an out-of-the-box solution that assumes you are running in a Unix-like environment.

First run the following on the command line:

echo 'option = {' > file.py
sed 's/ /: /' file >> file.py
echo '}' >> file.py

You have now created an importable Python script file.py from the original file. You can now do

import file

in your driver script.

If formatting is important, you may want to use the following sed command as an alternative:

sed -e 's/ /: /' -e 's/^/    /' file.txt
分享给朋友:
您可能感兴趣的文章:
随机阅读: