'How does this code for creating multiple variables within a dictionary work? [duplicate]
I've been trying to find a way to create variables from within a for loop without needing to know in advance how many variables I will need to create. I've run into examples such as:
a_dictionary = {}
for number in range(1,4):
a_dictionary["key%s" %number] = "abc"
print(a_dictionary)
{'key1': 'abc', 'key2': 'abc', 'key3': 'abc'}
Another I have seen is
d={}
for x in range(1,10):
d["string{0}".format(x)]="Variable1"
print(d)
{'string1': 'Variable1', 'string2': 'Variable1','string3': 'Variable1', 'string4': 'Variable1', 'string5':'Variable1', 'string6': 'Variable1', 'string7': 'Variable1','string8': 'Variable1', 'string9': 'Variable1'}
My question is, how does this work, and is there a way to do something similar, like global variables without the need for a dictionary? For example, to do something like
random_list = [23,67,12,93,5,420]
for i in range(0,6):
variable_i = random_list[i]
print(variable_i)
23
67
12
93
5
420
to achieve the same thing as a manual assignment such as
variable_0 = 23
variable_1 = 67
variable_2 = 12
variable_3 = 93
variable_4 = 5
variable_5 = 420
Solution 1:[1]
The module namespace is a dictionary and you can get it via globals(). Using f-strings (the newest way to build strings from variables) and the enumerate function instead of range, you could
>>> random_list = [23,67,12,93,5,420]
>>> for i, val in enumerate(random_list):
... globals()[f"variable_{i}"] = val
...
>>> variable_0
23
The for can be replaced by using the dictionary's "update" method
globals().update((f"variable_{i}", val) for i, val in enumerate(random_list))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tdelaney |
