Daniel Arges
Daniel Arges

Reputation: 365

How to sum a single value to a single dictionary item?

Seems extremely easy, although I haven´t find the answer easily.

Take this dict:

my_dict = {'my_key':1.5}

Take this float:

f = 0.5

How can I add this float value to a single dictionary item?

This is my wrong code, but you get the idea:

my_dict['my_key'][0] = my_dict['my_key'][0] + f

Upvotes: 0

Views: 56

Answers (4)

Jonas Ferreira
Jonas Ferreira

Reputation: 281

You can use the update method of dictionaries:

>>> my_dict = {'my_key':1.5}
>>> f = 0.5

>>> new_value = my_dict['my_key'] + f

>>> my_dict.update({'my_key': new_value})

Upvotes: 0

Sandeep Mohanty
Sandeep Mohanty

Reputation: 1552

the code will be:

ans= my_dict['my_key'] + f

print(ans)

Upvotes: 0

Allprod
Allprod

Reputation: 443

You access dictionary items by supplying the item key so in this case just type:

my_dict['my_key'] = my_dict['my_key'] + f

and you're golden refer Here for more on how to use dictionaries

Upvotes: 2

Shawn Ramirez
Shawn Ramirez

Reputation: 833

I think it was just syntax on a) accessing the value for that key, b) using it as a float and c) updating the original key's value?

my_dict = {'my_key':1.5}

f= 0.5

my_dict['my_key'] = float(my_dict['my_key'])+ f

print(my_dict)

Upvotes: 0

Related Questions