0

I am a complete newbie to Python.

I have data in the following format :

ontology = {


  'OBJECT' :


    {'IS-A' : {'VALUE' :'ALL'},


     'SUBCLASSES' : {'VALUE' :['PHYSICAL-OBJECT',


                               'MENTAL-OBJECT','SOCIAL-OBJECT']},


     'THEME-OF' : {'sem' : 'EVENT'}},





 'PHYSICAL-OBJECT' :


    {'IS-A' : {'VALUE' :'OBJECT'},


     'SUBCLASSES' : {'VALUE' :['ANIMATE', 'INANIMATE']},


     'THEME-OF' : {'sem' : 'EVENT'}},
}

I want to load all this data into a Python dictionary. But I get an error if I used the eval(file.read()).

Is there any way I can do this? (I don't have any class definitions)

Sheno
  • 19
  • 6
  • What error so you get ? You should try ast.literal_eval() . – Anand S Kumar Sep 23 '15 at 03:21
  • Traceback (most recent call last): File "Test.py", line 20, in getData() File "Test.py", line 11, in getData dict = eval(file.read()) File "", line 15 ontology = { ^ SyntaxError: invalid syntax – Sheno Sep 23 '15 at 03:28

2 Answers2

0

Eval is generally a bad plan for security reasons, and you'd be better serialising with pickle or JSON.

But it won't read because you can't assign variables with = using eval(). If that's the exact format, you could try skipping after the = and eval()ing the rest:

data = open('data.txt').read()
ontology = eval(data[data.find('=')+1:])
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
0

Using eval is a really bad idea. Use ast.literal_eval instead.

For that to work, you must get rid of ontology = part, it's not needed. Leave only a dictionary itself in a file.

Then, load it as follows:

>>> import ast
>>> with open('data.txt') as file:
...     data = ast.literal_eval(file.read())
... 
>>> data
{'PHYSICAL-OBJECT': {'IS-A': {'VALUE': 'OBJECT'}, 'THEME-OF': {'sem': 'EVENT'}, 'SUBCLASSES': {'VALUE': ['ANIMATE', 'INANIMATE']}}, 'OBJECT': {'IS-A': {'VALUE': 'ALL'}, 'THEME-OF': {'sem': 'EVENT'}, 'SUBCLASSES': {'VALUE': ['PHYSICAL-OBJECT', 'MENTAL-OBJECT', 'SOCIAL-OBJECT']}}}
Community
  • 1
  • 1
alexanderlukanin13
  • 4,577
  • 26
  • 29