Python

时间:2017-08-31 22:24:02

标签: python dictionary import global-variables

我正在开发一个包含多个脚本的项目,所以我在一个名为settings.py的文件中设置了一堆全局变量。一个全局变量称为dataSource,它在两个不同的数据源之间切换,我们称之为“A”和“B”。

 global dataSource
 dataSource="A" 

我有两个不同的词典,每个数据源一个,它将通用变量名称映射到A和B中的特定变量名称(所有数据都在同一个数据帧中,只有A和B特定的名称,并且没有模式到命名)。

 A={"GDP":"GDP 1", "Inflation":"A Inf", "Unemployment": "Unemp"}
 B={"GDP":"Gross Domestic Product","Inflation":"Infl","Unemployment":"Unemployment B"}

我脚本的其余部分仅使用通用字典键名作为变量,但我希望能够使用

切换所有输入
import settings
df[settings.dataSource["GDP"]] 

我期待Python将其读作

 df[A["GDP"]] --> df["GDP 1"]

相反,我得到一个TypeError

  string indices must be integers, not str

我知道这是因为Python将A视为一个字符串,而不是一段代码来执行。我尝试使用exec(),但这似乎没有帮助。有关如何调试/如何以不同方式编码的任何想法?

1 个答案:

答案 0 :(得分:0)

您正在阅读字符串并期望python将其理解为字典。

最好只将字典本身存储在配置文件中,然后根据需要导入字典。

settings.py

_A = {"GDP":"GDP 1", "Inflation":"A Inf", "Unemployment": "Unemp"}
_B = {"GDP":"Gross Domestic Product","Inflation":"Infl","Unemployment":"Unemployment B"}

datasource = _A # change this to _B when you need to 

main.py

from settings import datasource
print(df[dataSource["GDP"]])