[英]Importing a variable from another file in Python
I have two files - abc.py and main.py .我有两个文件 - abc.py和main.py 。 My aim is to import the whole dictionary from another file.
我的目标是从另一个文件中导入整个字典。 To explain it better, a user enters a input(lets say English) and this should be import variable English from the abc.py into main.py .
为了更好地解释它,用户输入一个输入(比如说英语),这应该是将变量 English 从abc.py导入main.py 。 Below is the code I tried, it's giving me an error.
下面是我试过的代码,它给了我一个错误。
*/abc.py */abc.py
English = {1:"Hello", 2:"World"}
Italian = {1:"Bonjour", 2:"Mondo"}
*/main.py */main.py
import abc
option=input("Please Enter 'English' or 'Italian': ")
selectedLanuage = abc.option
print(selectedLanuage)
One workaround I can think of is separating the access of the dictionary and the input.我能想到的一种解决方法是将字典和输入的访问分开。
option=input("Please Enter 'English' or 'Italian': ")
if option == "English":
selectedLanguage = abc.English
elif option == "Italian":
selectedLanguage = abc.Italian
print(selectedLanguage)
EDIT:编辑:
languages = {"English": abc.English, "Italian": abc.Italian}
option = input("Please Enter 'English' or 'Italian': ")
selectedLanguage = languages[option]
First, I highly recommend you name your current abc
file something else since abc
is actually a standard library module .首先,我强烈建议您将当前的
abc
文件命名为其他名称,因为abc
实际上是一个标准库模块。 Assuming you have the following in languages.py
假设您在
languages.py
中有以下内容
English = {1: "Hello", 2: "World"}
Italian = {1: "Bonjour", 2: "Mondo"}
and the following in main.py
以及
main.py
中的以下内容
from languages import English, Italian
languages_by_choice = {
'English': English,
'Italian': Italian
}
option = input('Please enter "English" or "Italian": ')
selected_language = languages_by_choice.get(option)
if not selected_language:
raise ValueError('Invalid language selection: {}'.format(option))
print(selected_language)
your program would be used something like this:您的程序将使用如下方式:
~ python3 main.py
Please enter "English" or "Italian": English
{1: 'Hello', 2: 'World'}
~ python3 main.py
Please enter "English" or "Italian": Italian
{1: 'Bonjour', 2: 'Mondo'}
~ python3 main.py
Please enter "English" or "Italian": asdf
Traceback (most recent call last):
File "stackoverflow.py", line 11, in <module>
raise ValueError('Invalid language selection: {}'.format(option))
ValueError: Invalid language selection: asdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.