0

I am working on a project with multiple scripts, so I set up a bunch of global variables inside a file called settings.py. One global variable is called dataSource, which toggles between two different data sources, lets call them "A" and "B".

 global dataSource
 dataSource="A" 

I have two different dictionaries, one for each datasource which maps generic variable names to specific variable names from A and B (all the data is in the same dataframe, with just A and B specific names, and there is no pattern to the naming).

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

The rest of my script only uses the generic dictionary key names as variables, but I would like to be able to toggle all the inputs by using

import settings
df[settings.dataSource["GDP"]] 

I was expecting Python to read this as

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

Instead I am getting a TypeError

  string indices must be integers, not str

I know this is because Python is seeing A as a string, rather than a piece of code to execute. I tried playing around with exec(), but that didn't seem to help. Any thoughts on how to debug/how to code this differently?

cs95
  • 379,657
  • 97
  • 704
  • 746
LauraF
  • 345
  • 2
  • 5
  • 11

1 Answers1

0

You're reading in a string and expecting python to understand it as a dictionary.

You're better off just storing the dictionaries themselves in your config file, and then importing those on a need-to-need basis.

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"]])
cs95
  • 379,657
  • 97
  • 704
  • 746