1

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)

1 Answers1

0

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)
Dharman
  • 30,962
  • 25
  • 85
  • 135
unddoch
  • 5,790
  • 1
  • 24
  • 37
  • But what does the locals() function do? Also, how are you updating the variables just by making a string instead of the variable name? – Jackbaklava Nov 07 '20 at 19:54
  • I linked the python documentation about `locals()`, so you can read about it there. I repeat my suggestion not to use this as a real-world solution to a real-world problem - there is probably a better, different way to do it without updating "lists of variables" – unddoch Nov 07 '20 at 20:00
  • Wait a minute, I changed the locals() to globals(), but the program is still working. So, what’s the difference? – Jackbaklava Nov 07 '20 at 20:12
  • Different scopes. https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules – unddoch Nov 07 '20 at 21:17