suppose I have lists of strings like this
list1 = ["x","y","z"]
so how can create empty dictionaries like x = {}
, y = {}
and z = {}
by iteration
Following method does nothing:
for i in list1:
i = dict()
suppose I have lists of strings like this
list1 = ["x","y","z"]
so how can create empty dictionaries like x = {}
, y = {}
and z = {}
by iteration
Following method does nothing:
for i in list1:
i = dict()
As recommended do not dynamiclly create variable from strings
This said, you may store this in a dict
to store, then associate an empty dict for each key
result = {}
for idx in list1:
result[idx] = {}
print(result)
# {'x': {}, 'y': {}, 'z': {}}
Check out the following code:
list1 = ["x","y","z"]
for i in list1:
globals()[i] = dict()
This will give you:
x = {}
y = {}
z = {}
To check the output and its types you can do the following:
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
You can use the built-in exec
function.
For example, exec("x=3")
creates the x
variable, assigning to it the value 3
.
Your specific example can be solved like this:
for var in list1:
exec(var + "={}")
This dynamic creation of variable names is not advised most of the time. Check Creating dynamically named variables from user input.
I am not sure what you are attempting to do but would this is a possible approach.
list1 = ["x","y","z"]
d = {}
for i in list1:
d[i] = {}
You would get a dict with an empty dict inside for each of your strings.