0

a_dictionary has DataFrames in it.

How do I automate the extraction of these values into the variables that hold the names of keys themselves?

Basically, automate the process below, but with more DataFrames:

df1 = a_dictionary['df1']
df2 = a_dictionary['df2']
df3 = a_dictionary['df3']

I tried:

for i in a_dictionary:
    i = a_dictionary[i]

pe = 0
for i in a_dictionary:
    i = list(a_dictionary.keys())[pe]
    pe += 1

pe = 0
for i in a_dictionary:
    if pe < len(a_dictionary):
        i = list(a_dictionary.keys())[pe]
        pe += 1
    else:
        break
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • 2
    Short answer: **don't**. It is considered **very bad practice** to dynamically generate variable names. You have a container, why not using it? – mozway Mar 29 '22 at 13:50
  • what container? and i still would like to dynamically generate variable names, because the list is pretty short and names are very distinct – Stunedt Studencheskiy Mar 29 '22 at 13:51
  • See [this](https://stackoverflow.com/questions/41156401/create-dynamic-variables-in-python-from-dictionary-keys-in-for-loop) question – not_speshal Mar 29 '22 at 13:52
  • do you mean 'a_dictionary['df3']' by container for exmaple? – Stunedt Studencheskiy Mar 29 '22 at 13:52
  • `a_dictionary` is your container. if you have just a few variables, simply do what you did: `df1 = a_dictionary['df1']`, this is explicit. If you have too many that it becomes a burden, this is a sign you don't need variables but a container (read the duplicate). – mozway Mar 29 '22 at 13:52
  • @not_speshal thank you so much, this worked perfectly, i spent whole night trying out different loops ... turns out the answer is so simple. – Stunedt Studencheskiy Mar 29 '22 at 13:57
  • @mozway i wanted to use it for different files and generate different dataframes, so it would take me some time everytime to do this – Stunedt Studencheskiy Mar 29 '22 at 13:57
  • I still discourage you do to it, the method linked by not_speshal doesn't always work and can have side effects, you need to know it! If you need to do something repetitive, write a function – mozway Mar 29 '22 at 14:00
  • @mozway thank you, noted that. But I am not sure i know how to write this code in function without using globals? – Stunedt Studencheskiy Mar 29 '22 at 16:49
  • don't think of the variable, think of what you want to do with it. You can do the same with a container. You should provide more details about your end goal. – mozway Mar 29 '22 at 17:24
  • Its fitting prices of bunch of commodities to bunch of ETFs, each of which were in these DataFrames. Of course i coudl have used the original "a_dictionary['df1']" but it is much more convenient to simply use the variables as "df1" – Stunedt Studencheskiy Mar 29 '22 at 17:27

0 Answers0