如何将数据结构(例如 dict)从单独的文件导入或包含到 Python 文件中 [英] How to import or include data structures (e.g. a dict) into a Python file from a separate file
问题描述
我知道我可以使用 import MyModuleName
从通用文件中包含 Python 代码 - 但我如何只导入一个 dict?
I know I can include Python code from a common file using import MyModuleName
- but how do I go about importing just a dict?
我要解决的问题是我有一个 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'}
如何从 script.py 中访问 airportCode
dict?
How do I access the airportCode
dict from within script.py?
推荐答案
直接导入
import myDict
print myDict.airportCode
或者,更好
from myDict import airportCode
print airportCode
小心将两个脚本放在同一个目录下(或者制作一个 python 包,一个带有 __init__.py
文件的子目录;或者把 script.py 的路径放在 PYTHONPATH 上;但是这些是高级选项",只需将其放在同一目录中就可以了).
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).
这篇关于如何将数据结构(例如 dict)从单独的文件导入或包含到 Python 文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!