In Python, the separation of what is given (text strings, for example) and what is code is very rigid - which sets it apart from PHP, Perl and Shel Script.
So you can create dynamic variable names, as you do - but notice that the name is passed in a string:
globals()['volume_%s' % nome] = []
(The %
operator with two strings creates another string that is used as a key in the global dictionary)
So volume_%s.append(vol)
is simply wrong. Coincidentally, this is not a syntax error: the language will try to use the %
operator with the variables volume_
and s
, and you should see NameError
(why volume_
with nothing does not exist).
So, to make it work what you want, you would just access the variables in the same way you created them, like keys in the global dictionary. To not have to repeat globals()
on each line, you can assign this dictionary to a short variable:
g = globals()
g['volume_%s' % nome] = []
...
for i in serie:
g['volume_%s'% nome].append(int(i['Volume']))
And that's the answer to your question.
Now a good practice advice, which must have become very visible at this point: You should use variables for names that you know when you are coding and have fixed function - and use dictionaries for names that you will receive dynamically.
In this case, for example, you gain nothing in saving your data in the global dictionary (the dictionary that is returned by globals()
) and any dictionary you create yourself. (You actually get a chance to overwrite some other variable unexpectedly with direct writing in globals()
and have a very difficult debugging bug.)
With a 'common' dictionary you can even store all your data in a dictionary where there is a key for each name, and it is easier to view and view your data: and only adapt the view (or output to file) after:
dados = {}
def desmenbrando_dados(acao,date1,date2, nome):
dados_locais = dados[nome] = {}
dados_locais['volume'] = []
...
for i in serie:
vol = int(i['Volume'])
dados_locais['volume'].append(vol)
Ready - data for all series will be available in the dictionary - this global yes - fixed-name "data". Better yet, you can make the function return the dados_locais
dictionary and dispense with the use of dados
globally: whites desmembrando_dados
is responsible for consolidating the complete dictionary of each company. In short, there are several possibilities - but none in which you're going to take any benefit from dynamically creating the names of the variables themselves - for the simple fact that you would have to write the same code back to read the data from those dynamic variables. p>