1

Let's say I read from a file, called 'info.dat', containing this:

[{'name': 'Bob', 'occupation': 'architect', 'car': 'volvo'}, {'name': 'Steve', 'occupation': 'builder', 'car': 'Ford'}]

How could I read this and turn it into a list of dictionaries? If I do this:

with open('info.dat') as f:
    data = f.read()

It just reads it into a single string, and even if I do this to break it up:

data = data[1:-1]
data = data.split('},')

I still have to get it into a dictionary. Is there a better/cleaner way to do this?

4

3 回答 3

4

使用ast.literal_eval

import ast
with open('info.dat') as f:
    data = ast.literal_eval(f.read())

正如文档中所说,这比文档更安全,因为它“安全地评估 [s] 表达式节点或包含 Python 表达式的字符串”。

如果它不安全,它将引发错误。

于 2013-07-22T11:48:19.737 回答
4

使用ast.literal_evalwhich 可以读取简单的 Python 文字,例如 dicts/tuples/lists - 虽然它不那么“强大”,因为eval它更安全,因为它的限制性更强。

from ast import literal_eval
with open('yourfile') as fin:
    your_list = literal_eval(fin.read())
于 2013-07-22T11:48:20.323 回答
1

也许使用 eval -

eval("ld ="+open("info.dat").read())

然后使用ld变量访问列表

于 2013-07-22T11:46:22.450 回答