Search code examples
pythonpython-3.xdictionarytext

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)

Solution

  • Your text file is a valid Python code, so if it is from a trusted source, you can simply do:

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

    and the variable d would be loaded with the 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. 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:

    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:

    {'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}