Dynamically allocate variables on a for loop in python
<p>On the code below, the list 'anos' shall be defined by the user and can take an arbitrary number of years. </p>

<p>However, for each year within the 'anos' list, a new variable has to be assigned at the beginning of FOR loop. If anos = ['2008', '2009], then the for loop would be: for [a,b].. and the data += would also only use a and b.</p>

<p>Is it possible to dynamically allocate such variables depending on the number of items with the 'anos' list? Does the FOR function accept it or do I have to resort to another tool in itertools?</p>

<pre><code>def gv(var):
dd, aa, bb, cc, anos = {}, [], {}, {}, ['2006','2007','2008','2009','2010','2011','2012','2013','2014','2015']

for i in anos:
    resp = requests.get('http://www.sidra.ibge.gov.br/api/values/t/1612/n3/all/v/'+var+'/p/' + i + '/C81/2713/f/c')
    dd[i] = json.loads(resp.text.encode('utf8'))

anos_tuple = tuple((dd[i]) for i in anos) #ie: (dd['2006], dd['2007']...)

for [a,b,c,d,e,f,g,h,i,j] in zip(*anos_tuple): # uma letra para cada ano
    data = a['D1C']
    data += ','.join([a['V'], b['V'], c['V'], d['V'], e['V'],
                      f['V'], g['V'], h['V'], i['V'], j['V']])
</code></pre>

<blockquote>
  <p>If anos = ['2008', '2009], then the for loop would be: for [a,b].. and the data += would also only use a and b</p>
</blockquote>

<p>So the list [a,b ] can become [a, b, c ] when there are 3 years and so on.</p>

<p>In that case, translate your last for loop into</p>

<pre><code>for row in zip(*anos_tuple):
    # a is row[0]
    data = row[0]['D1C']

    # a['V'], b['V'] etc is row[0]['V'], row[1]['V']
    data += ','.join([ i['V'] for i in row ])
</code></pre>

python loops tuples itertools