简体   繁体   English

如何从文本文件中读取字典?

[英]How to read the dictionary from text file?

I have a text file in the below format 我有以下格式的文本文件

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}

How do I read the dictionary to find the value a particular value? 如何阅读字典以找到特定值?

I have tried the below code 我已经尝试了以下代码

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)

Your text file is a valid Python code, so if it is from a trusted source, you can simply do: 您的文本文件是有效的Python代码,因此,如果来自受信任的来源,则只需执行以下操作:

with open("filename") as f:
    exec(f.read())

and the variable d would be loaded with the dict. 并且变量d将被加载dict。

If the text file is not from a trusted source, however, you can use ast.parse to parse the code, then use ast.walk to traverse the abstract syntax tree and look for a Dict node. 但是,如果文本文件不是来自受信任的来源,则可以使用ast.parse解析代码,然后使用ast.walk遍历抽象语法树并查找Dict节点。 For security reasons, make sure the dict node does not contain any Call node before wrapping it as the body of an Expression node and compiling it for eval to turn it into a real dict stored in variable d : 出于安全原因,在将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.')

Given your sample input, d would become: 给定您的样本输入, 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}

You need to iterate over both the keys and values: 您需要遍历键和值:

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)

Also, that file looks like a valid JSON object, so you should probably use json.load over ast.literal_eval . 此外,该文件看起来像一个有效的JSON对象,所以你应该使用json.load超过ast.literal_eval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM