本文介绍了如何从单独的文件将数据结构(例如dict)导入或包含到Python文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用 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需要在一个可编辑位置的文件中,而实际的脚本在另一个文件中。 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'}

如何从中访问 airportCode dict script.py

How do I access the airportCode dict from within script.py?

推荐答案

只需导入

import script
print script.airportCode

或,更好

from script import airportCode
print airportCode

小心将两个脚本放在同一目录上(或制作ap ython包,一个带有 __ init __。py 文件的子目录;或者将路径放到PYTHONPATH上的script.py;但这些都是高级选项,只需将它放在同一个目录中就可以了。

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文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:37