[英]How to read the dictionary from text file?
我有以下格式的文本文件
d = {'EMS':1,'ESC': 2, 'HVAC': 3,'IC' : 4,'ICU' : 5,'IS' : 6,'ITM' : 7,'MBFM' : 8,'PKE' : 9,'RPAS' : 10,'RVC' : 11,'SAS' : 12,'SRS' : 13,'TCU' : 14,'TPMS' : 15,'VCU' : 16,'BMS' : 17,'MCU' :18,'OBC' :19}
如何阅读字典以找到特定值?
我已经尝试了以下代码
with open(r"filename","r") as f:
data = ast.literal_eval(f.read())
print(data)
for age in data.values():
if age == search_age:
name = data[age]
print (name)
您的文本文件是有效的Python代码,因此,如果来自受信任的来源,则只需执行以下操作:
with open("filename") as f:
exec(f.read())
并且变量d
将被加载dict。
但是,如果文本文件不是来自受信任的来源,则可以使用ast.parse
解析代码,然后使用ast.walk
遍历抽象语法树并查找Dict
节点。 出于安全原因,在将dict节点包装为Expression
节点的主体并将其编译为eval
以将其转换为存储在变量d
的实际dict之前,请确保dict节点不包含任何Call
节点:
import ast
with open("filename") as f:
for node in ast.walk(ast.parse(f.read())):
if isinstance(node, ast.Dict) and \
not any(isinstance(child, ast.Call) for child in ast.walk(node)):
d = eval(compile(ast.Expression(body=node), '', 'eval'))
break
else:
print('No valid dict found.')
给定您的样本输入, d
将变为:
{'EMS': 1, 'ESC': 2, 'HVAC': 3, 'IC': 4, 'ICU': 5, 'IS': 6, 'ITM': 7, 'MBFM': 8, 'PKE': 9, 'RPAS': 10, 'RVC': 11, 'SAS': 12, 'SRS': 13, 'TCU': 14, 'TPMS': 15, 'VCU': 16, 'BMS': 17, 'MCU': 18, 'OBC': 19}
您需要遍历键和值:
with open('filename') as f:
data = ast.literal_eval(f.read())
print(data)
for name, age in data.items():
if age == search_age:
print(name)
此外,该文件看起来像一个有效的JSON对象,所以你应该使用json.load
超过ast.literal_eval
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.