简体   繁体   中英

Reading a list from a file, and converting it into a list of Python dictionaries

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?

Use ast.literal_eval :

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

As said in the docs, this is much more safer than the docs as it "safely evaluate[s] an expression node or a string containing a Python expression".

If it is unsafe, it will raise an error.

Using ast.literal_eval which can read simple Python literals such as dicts/tuples/lists - while not as "powerful" as eval it is safer due to its more restrictive nature.

from ast import literal_eval
with open('yourfile') as fin:
    your_list = literal_eval(fin.read())

Maybe use eval -

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

Then access the list using ld variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM