Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through dictionary and change values

Tags:

python

Lets say I have a dictionary with names and grades:

{"Tom" : 65, "Bob" : 90, "John" : 80...}

and I want to take all the values in the dictionary and add 10% to each:

{"Tom" : 71.5, "Bob" : 99, "John" : 88...}

How can I do it through all the values in the dictionary?

like image 823
user1040563 Avatar asked Dec 01 '22 01:12

user1040563


1 Answers

Dict comprehension:

mydict = {key:value*1.10 for key, value in mydict.items()}

Pre 2.7 :

mydict = dict(((key, value*1.10) for key, value in mydict.items()))
like image 63
Vincent Savard Avatar answered Dec 06 '22 10:12

Vincent Savard