0

This question has been edited to include the answer.

Simple question. I would like to append a variable with the string from another variable. For example:

countries = ['USA','CAN','MEX']
df_imp_USA = read_csv(r'%s_final_forecasts.csv' % countries[0]);

What syntax would allow me to automatically change df_imp_USA according to the contents in countries? I need to do this because I want to put this line into a for loop. Thanks.

Answer

As the comments suggest, using dictionaries is preferable to creating new variables. I saw this in previous answers but couldn't figure out how to use dictionaries in my code. I include the syntax below in case it may help others.

df_imp = {} # define the dic
for country in countries:
    df_imp[country] = read_csv(r'%s_final_forecasts.csv' % country)

Now you can access the dict like this:

df_imp['USA']
Agrippa
  • 475
  • 2
  • 5
  • 13
  • 2
    This is a "variable variables" question. Use a dictionary. – timgeb Nov 15 '17 at 21:27
  • I know. I looked at that already but using dictionaries didn't make sense to me. – Agrippa Nov 15 '17 at 21:34
  • 1
    Using dictionary would be the best practice – Yuan Fu Nov 15 '17 at 21:37
  • Could you spell out how that would work in my case? – Agrippa Nov 15 '17 at 21:38
  • Just use a dictionary. They are a *core* feature of Python, and now is *always* a good time to learn how to use them. – juanpa.arrivillaga Nov 15 '17 at 21:39
  • 1
    First, make your `dict`: `df_imp = {}`, then `for country in countries: df_imp[country] = pd.read_csv(r'%s_final_forecasts.csv' % country)` Now you can access the `dict` like this: `df_imp['USA']` or `df_imp['CAN']` – juanpa.arrivillaga Nov 15 '17 at 21:41
  • @juanpa.arrivillaga Thanks. I actually understand the dictionary method now - and have got it working in my code. It solves some of my problem but maybe not all. Have to go to bed now but I'll look into it tomorrow evening. Tks again. – Agrippa Nov 15 '17 at 21:59
  • @juanpa.arrivillaga Thx for the code. It actually works really well. I reduced the amount of lines in my code by a factor of 3 in some parts. I updated the question to include the answer. Cheers. – Agrippa Nov 18 '17 at 09:59

0 Answers0