Skip to content
Advertisement

Use “for loop” to create newly named variables from the keys of a dictionary

I want to use a for loop to create newly named variables from the keys, which can then be retrieved globally down the road. To define the variable before with None, has unfortunately brought nothing. Also, with Global I did not get further, but possibly I used it also wrong. I have googled a lot, but unfortunately I couldn’t get hold of the solution. Is there any trick how I can retrieve the new variables in the later course?

LAeq = { 'Januar': [69.1, 57.9, 58.3, 55.6],
         'Februar': [66.7, 65.5, 63.5, 62.4] }

anzahl_Januar = None #anzahl is number in English
print ("{:<9} {:<5} {:<9}".format('Monat','Tage','Prozent'))

for key in LAeq.keys():
    for value in LAeq[key]:
        anzahl_key = 0
        for i in LAeq[key]: #LAeq['Januar']
            if i > 63 :
                anzahl_key = anzahl_key + 1
    print("{:<9} {:<5} {:<9}".format(key, anzahl_key, "{:.1%}".format(anzahl_key/len(LAeq[key]))))
    
print(anzahl_Januar)

Obviously the dictionary is much larger, I just put down an example here. I am thankful for any advice! :)

Advertisement

Answer

You can use the exec command, like this:

dict={}
for i in range (10):
    key=str("x"+str(i))
    dict[key]=i
for key,value in dict.items():
    exec(f'{key}={value}')

Try adjusting this to your data.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement