Updating Variables From a Dictionary In a For Loop

Hhh Qadir

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)

unddoch

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.

edited at
0

Comments

0 comments
Login to comment

Related

Preventing loop from updating all sub dictionary values

Updating variables in a for loop

updating dictionary dose not work in the loop

Python dictionary not updating as expected in a loop

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

Updating variables in for loop with PL/SQL

C++ Variables not updating in loop

For loop updating dictionary values but not affecting output

Python updating dictionary and appending at the end of list with loop

Why is my dictionary not updating in this while loop?

Simultaneously updating two variables in an Excel VBA for loop

Calling a method with a for loop inside, not updating variables

Variable not updating from While loop

Creating variables from a python dictionary with multiple values for each key using a for loop

Updating values in a dictionary with values from a list

Updating text file from the python dictionary

Updating variable value from dictionary and best practice

Updating the values of groups in a column from a dictionary

Django - For loop for two variables passed in a dictionary

Removing words from lemmatisation dictionary/updating lemma dictionary in textstem

Updating all keys of a nested dictionary from another dictionary

Creating a Nested Dictionary from For Loop

Dictionary output from for-loop

Multiple Nested dictionary From a loop

Speed up a nested Python loop while updating a dictionary

Updating global variables from try block

Android Studio variables not updating from function call

updating label variables from a running timer

Extract key1:value1 from dictionary 1 and key1:value1 from dictionary 2, assign them to 4 different variables, loop