in this piece of code I want to update some varaiables(x
and y
in this case) by looping through a dictionary that has the variables hashed to the new values I want to assign them to. But when I try using a for
loop for looping through and assigning the variables, I only end up updating the temporary loop var
and not the actual keys/variables. Please help me update these variables by somehow looping through the dictionary.
x = 5
y = 10
dict1 = {x : 5,
y : 10
}
for var in dict1:
var -= dict1[var]
print(x,y)
print(dict1)
I think you have misconceptions on how dictionaries and variables work. By writing
dict1 = {x: 5}
You're writing the equivalent of
dict1 = {5: 5}
Because you're using the value x and not the variable name x.
What you want to do might be achieved by using locals()
, but I advise against it - there is almost always a simpler, less "dark-magic" solution. Nevertheless, an example:
x, y = 5, 10
dict1 = {
"x" : 5,
"y" : 10
}
for var in dict1:
locals()[var] -= dict1[var]
print(x,y)
print(dict1)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments