Python:使用字典格式从文本/文件创建字典

Jar*_*red 22 python dictionary file external

我想从我拥有的文本文件中创建一个字典,其内容是"字典"格式.以下是该文件包含的示例:

{'fawn':[1],'sermersheim':[3],'sonji':[2],'scheuring':[2]}

除此之外,它包含125,000个条目.我能够使用read()读取文本文件,但是即使我使用read()初始化变量,它也会创建文件的文本文本的变量

dict = {}

Ste*_*der 29

你可以使用eval内置的.例如,如果每个字典条目位于不同的行上,这将起作用:

dicts_from_file = []
with open('myfile.txt','r') as inf:
    for line in inf:
        dicts_from_file.append(eval(line))    
# dicts_from_file now contains the dictionaries created from the text file
Run Code Online (Sandbox Code Playgroud)

或者,如果文件只是一个大字典(即使在多行),您可以这样做:

with open('myfile.txt','r') as inf:
    dict_from_file = eval(inf.read())
Run Code Online (Sandbox Code Playgroud)

这可能是最简单的方法,但它并不是最安全的.正如其他人在答案中提到的那样,eval存在一些固有的安全风险 JBernardo提到的另一种方法是使用ast.literal_eval比eval更安全的方法,因为它只会评估包含文字的字符串.您可以在导入模块后简单地替换eval上面示例中的所有调用.ast.literal_evalast

如果您使用的是Python 2.4,那么您将不会拥有该ast模块,并且您不会有with语句.代码看起来更像是这样的:

inf = open('myfile.txt','r')
dict_from_file = eval(inf.read())
inf.close()
Run Code Online (Sandbox Code Playgroud)

别忘了打电话inf.close().with语句之美是他们为你做的,即使with语句中的代码块引发了异常.