I know I can include Python code from a common file using import MyModuleName - but how do I go about importing just a dict?
The problem I'm trying to solve is I have a dict that needs to be in a file in an editable location, while the actual script is in another file. The dict might also be edited by hand, by a non-programmer.
script.py
airportName = 'BRISTOL'
myAirportCode = airportCode[airportName]
myDict.py
airportCode = {'ABERDEEN': 'ABZ', 'BELFAST INTERNATIONAL': 'BFS', 'BIRMINGHAM INTERNATIONAL': 'BHX', 'BIRMINGHAM INTL': 'BHX', 'BOURNMOUTH': 'BOH', 'BRISTOL': 'BRS'}
How do I access the airportCode dict from within script.py?
解决方案
Just import it
import script
print script.airportCode
or, better
from script 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 it'll be fine).