Search code examples
pythonword2vec

How to assign dynamic variables in a for loop in python


I have five models for five years as follows.

word2vec_files = ["word2vec_2011", "word2vec_2012", "word2vec_2013", "word2vec_2014", "word2vec_2015"]
years = [2011, 2012, 2013, 2014, 2015]

I want to open each model as model_2011, model_2012, model_2013, model_2014, model_2015.

Currently I am doing it one by one as follows.

model_2011 = word2vec.Word2Vec.load("word2vec_2011")
model_2012 = word2vec.Word2Vec.load("word2vec_2012")
model_2013 = word2vec.Word2Vec.load("word2vec_2013")
model_2014 = word2vec.Word2Vec.load("word2vec_2014")
model_2015 = word2vec.Word2Vec.load("word2vec_2015")

Now I want to imitate the same process using a for loop.

for i, word2vec_file in enumerate(word2vec_files):
    "model_"+str(years[i]) = word2vec.Word2Vec.load(word2vec_file)

However, I get the following error SyntaxError: can't assign to operator. I am wondering how to assign dynamic variables in a for loop in python.

I am happy to provide more details if needed.


Solution

  • Unfortunately you can't create variable from strings like that; but you can use a dictionary, and add keys/values to it:

    years = [2011, 2012, 2013, 2014, 2015]
    
    models = {}
    
    for year in years:
      models[year] = word2vec.Word2Vec.load("word2vec_%s" % year)
    
    print(models)
    

    That way, you can access the year on models to get what you need.

    You could do the same thing with a dictionary comprehension:

    years = [2011, 2012, 2013, 2014, 2015]
    
    models = {
      year: "word2vec_%s" % year
      for year in years
    }
    
    print(models)