[英]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.