In Python, the separation of what is given (text strings, for example) and what is code is very rigid - what differentiates it 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)
Thus volume_%s.append(vol)
is simply wrong. By coincidence it is not a syntax error: the language will try to use the operator %
with the variables volume_
and s
, and you should see a NameError
(why the variable volume_
with nothing there is no).
So to make it work what you want, it would just be to access the variables in the same way that you created them, as keys in the global dictionary. So I don’t have to keep repeating globals()
in each row, 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 piece of good practice advice, which should have become very visible by now: You should use variables for names that you know when you’re coding and have a fixed function - and use dictionaries for names that you’ll receive dynamically.
In this case, for example, you gain nothing by storing your data in the global dictionary (the dictionary that is returned by globals()
) and some dictionary of your own. (In fact, you get yes: the chance to over-write some other variable unexpectedly with direct writing on globals()
and have a very difficult bug to debug).
With a 'common" dictionary you can even save all your data in a dictionary where there is a key for each name, and it is easier to view and see your data: and only adjust 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 - the data of all series will be available in the dictionary -this global yes - fixed name "data". Better yet, you can make the function return the dictionary dados_locais
and dispense with the use of dados
entirely global: who calls the desmembrando_dados
is responsible for consolidating the complete dictionary of each company. In short, it has several possibilities - but none where you will get any benefit from creating the names of the variables themselves dynamically - for the simple fact that you would have to write the same code back to read the data of these dynamic variables.
I believe you cannot use the character "%" in a variable.
– Rui Lima
is there any need to do it this way? I recommend that you create a class or even a dictionary to handle it.
– ppalacios
@jsbueno thank you very much for the help, you have not only answered my doubt and also gave me better ideas
– Pedro