I am going to read a file in python line by line and convert the line to a dictionary. The structure of the line is a little complex and I have no idea how can I convert that in a dictionary. Here is an example of first line of my file:
OrderedDict([('key', 'my_key'), ('rank', '2'), ('origin', 'IR'), ('num', '10'), ('num_2', '220'), ('same_array', ['a','b','d']), ('dif_array', ['g','h']), ('first_dic', OrderedDict([('name','ali'),('last','ali')])), ('num_', 0), ('response', OrderedDict([('ok_1', 0), ('red', 0), ('bad', 0)])), ('response_code', OrderedDict([('ok', 0), ('red', 0), ('bad', 0)]))])
I want to read first line and save that in a dictionary in a way that can use commands such as print my_dictionary['key']
which I want to got my_key
.
This is a very complex file which as you can see there are some inner array and dictionary in each line. I tried to use some command such as new_line = dict(item.split("=") for item in line.split(","))
or new_line = ast.literal_eval(line)
, but I got error because for example for first command as there are so many ,
inside the inner array, I do not got the good separation of the main dictionary items or for the second command I got this error:
ValueError: malformed string