How do I assign a dictionary value to a variable in Python?
Try This. It worked for Me.
>>> d = {'a': 1, 'b': 2}
>>> locals().update(d)
>>> print(a)
1
There are various mistakes in your code. First you forgot the =
in the first line. Additionally in a dict definition you have to use :
to separate the keys from the values.
Next thing is that you have to define new_variable
first before you can add something to it.
This will work:
my_dictionary = {'foo' : 10, 'bar' : 20}
variable = my_dictionary['foo']
new_variable = 0 # Get the value from another place
new_variable += variable
my_dictionary['foo'] = new_variable
But you could simply add new_variable
directly to the dict entry:
my_dictionary = {'foo' : 10, 'bar' : 20}
variable = my_dictionary['foo']
new_variable = 0 # Get the value from another place
my_dictionary['foo'] += new_variable