How to import or include data structures (e.g. a dict) into a Python file from a separate file

How to import or include data structures (e.g. a dict) into a Python file from a separate file

Just import it

import myDict
print myDict.airportCode

or, better

from myDict import airportCode
print airportCode

Just be careful to put both scripts on the same directory (or make a python package, a subdir with __init__.py file; or put the path to script.py on the PYTHONPATH; but these are advanced options, just put it on the same directory and itll be fine).

Assuming your import myDict works, you need to do the following:

from myDict import airportCode

How to import or include data structures (e.g. a dict) into a Python file from a separate file

Well, it doesnt need to be a .py file. You could just do:

eval(open(myDict).read())

Its a gaping security hole, though.

Another module you might want to look at is csv for importing CSV files. Then your users could edit it with a spreadsheet and you dont have to teach them Python syntax.

Leave a Reply

Your email address will not be published. Required fields are marked *