read a python dictionary (non standard file?)

Viewed 45

I am given an ASCI file with this format:

my_dictionary = {
    (1,0): "myvalue1",
    (1,1): "myvalue2"
}

if the file was like this:

{
    (1,0): "myvalue1",
    (1,1): "myvalue2"
}

then this code would work:

file = open(myfile, "r")
contents = file.read()
mydic = ast.literal_eval(contents)

but in my situation there is a crash due to the first line of the ASCII file, is there a way to read also the variable name?

1 Answers

A basic split on " = " will work in cases when you only have one "assignment" in your file, but if you have multiple instances of variable assignment with dictionaries, you can use itertools.groupby:

import itertools as it, ast, re
f = """
 my_dictionary = {
    (1,0): "myvalue1",
    (1,1): "myvalue2"
 }
 my_dictionary1 = {
    (1,0): "myvalue2",
    (1,1): "myvalue3"
 }
"""
r = [[a, list(b)] for a, b in it.groupby(filter(None, f.split('\n')), key=lambda x:'=' in x)]
d = {re.findall('\w+(?=\s\=)', r[i][-1][0])[0]:ast.literal_eval( \
        re.findall('\{(?:[\w\W]+)*', r[i][-1][0])[0]+'\n'.join(r[i+1][-1]))
           for i in range(0, len(r)-1, 2)}

Output:

{'my_dictionary': {(1, 0): 'myvalue1', (1, 1): 'myvalue2'}, 'my_dictionary1': {(1, 0): 'myvalue2', (1, 1): 'myvalue3'}}
Related