Python 如何将文件转换为字典?

Python 如何将文件转换为字典?,python,dictionary,Python,Dictionary,我想知道如何将.txt文件转换成Python字典。txt将存储地图的信息,其中包含一些名称和数字 .txt文件的外观示例: {“Jerry”:2353543} 我想将这个文本文件添加到python字典中。例如: file = open("random.txt",) read_file = file.read() #Then somehow add this read_file into the contact information to produce: contact_informatio

我想知道如何将.txt文件转换成Python字典。txt将存储地图的信息,其中包含一些名称和数字

.txt文件的外观示例:

{“Jerry”:2353543}
我想将这个文本文件添加到python字典中。例如:

file = open("random.txt",)
read_file = file.read()
#Then somehow add this read_file into the contact information to produce:
contact_information = {"Jerry" : 2345355}

在此结束时,代码将写回.txt文件。

如果文件内容仅由构成合法Python
dict
文本的字符串组成,该字符串递归地仅包含Python文本,则可以使用
ast.literal\u eval
进行此操作:

>>> data = '{"Jerry" : 2353543}'
>>> import ast
>>> d = ast.literal_eval(data)
>>> d
{'Jerry': 2353543}
>>> d['Jerry']  # It's an actual dict!
2353543
eval
不同,它不会带来与
eval
相同的安全/稳定性问题

json.load
/
json.load
也可以工作(在这种特定情况下也可以工作),但它通常更有限,因为它只允许json规范的一个小超集(例如允许整数作为键),但不支持
元组
字节
,等等。如果您的文件是json,使用它,但如果它是Python文本,请使用
ast.literal\u eval

使用模块从文件加载数据

>>> import json
>>> f = open("random.txt")
>>> contact_information = json.load(f, parse_int=int)
>>> contact_information
{'Jerry': 2353543}
>>> contact_information["Jerry"]
2353543

“包含映射”未定义输入格式。提供这一点和您的编码尝试,包括对您不起作用的内容的描述。那么您可能会有一个堆栈溢出问题。有没有办法将联系人信息转换为map@Learningcoding13:调用
json.load
返回该映射。