从文本文件到字典

时间:2016-07-11 14:52:03

标签: python python-3.x

我遇到了一些麻烦。我有一个.txt文件,内容如下:

    {'x': '1', 'y': 's'}

我想把它导入一个词典。我以前使用过此代码,但它不起作用:

     import json
     database = {}
     f = open('ds.txt','r')
     def load():
             database=json.load(open("ds.txt"))
             print(database)  
     load()

错误是这样的:

    Traceback (most recent call last):
    File "C:\Users\tan\Downloads\Compressed\project2\ct.py", line 11, in <module>
load()
    File "C:\Users\tan\Downloads\Compressed\project2\ct.py", line 6, in load
database=json.load(open("ds.txt"))
    File "C:\Users\tan\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 268, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
    File "C:\Users\tan\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
   File "C:\Users\tan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
   File "C:\Users\tan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
   json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

我也试过这个,但我认为它确实无效:

    database={}
    f=open("ds.txt","r")
    def load():
            o= f.read()
            database=o
            print(database)
    load()

这段代码属于更大的代码,所以如果需要整个代码来回答我的问题,请告诉我。 谢谢。

2 个答案:

答案 0 :(得分:3)

试试这个:

import ast
database = {}
f=open("ds.txt", "r")

def load():
    return ast.literal_eval(str(f.read()))

database = load()
print(database['y'])

How do you convert a stringed dictionary to a Python dictionary?

答案 1 :(得分:1)

您的JSON字符串无效。而不是单引号('),请用双引号(")替换它。

{"x": "1", "y": "s"}