Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign a dictionary value to a variable in Python?

I'm an amateur when it comes to programming, but I'm trying my hand at Python. Basically what I want to be able to do is use math on a dictionary value. The only way I could think to do it would be to assign a dictionary value to a variable, then assign the new value to the dictionary. Something like this:

my_dictionary {
    'foo' = 10,
    'bar' = 20,
    }

variable = my_dictionary['foo']
new_variable += variable
my_dictionary['foo'] = new_variable

However, when I try to assign a variable this way, I get a syntax error. Is there a better and straightforward way to do this?

EDIT: Also, I am only using this as an example. Let's say this is a block of code, not the entire program. The fact that new variable has not been declared is completely irrelevant, I just want to know how to perform math to a dictionary value. Also, I am attempting to access a dictionary outside of the function I have my code in.

like image 708
floatingeyecorpse Avatar asked Nov 16 '12 23:11

floatingeyecorpse


People also ask

Can the value in a Python dictionary be a variable?

Variables can't be dict values. Dict values are always objects, not variables; your numbers dict's values are whatever objects __first , __second , __third , and __fourth referred to at the time the dict was created. The values will never update on the dictionary unless you do it manually.

How do you assign a key to a variable in Python?

Use eval() to create dictionary keys from variables Call eval(variable_name) to return the value saved to variable_name . Use the dictionary assignment syntax dict[key] = value to assign value to key in dict .

How do you grab a value from a dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.


2 Answers

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
like image 119
nkr Avatar answered Sep 30 '22 20:09

nkr


Try This. It worked for Me.

>>> d = {'a': 1, 'b': 2}
>>> locals().update(d)
>>> print(a)
1
like image 40
ArunSK Avatar answered Sep 30 '22 19:09

ArunSK