user1040563
user1040563

Reputation: 5261

Loop through dictionary and change values

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?

Upvotes: 4

Views: 9184

Answers (4)

John Machin
John Machin

Reputation: 82924

You didn't ask for your dict to be replaced by a new one. The following code updates your existing dictionary. It uses basic looping techniques, which are as handy to know as well as comprehensions.

for name in grade_dict:
    grade_dict[name] *= 1.1

Upvotes: 5

KL-7
KL-7

Reputation: 47608

For python of version less than 2.7 you can use this:

result = dict((k, 1.1 * v) for k, v in h.items())

and for python 2.7 or higher you just do:

result = { k: 1.1 * v for k, v in h.items() }

Upvotes: 4

Vincent Savard
Vincent Savard

Reputation: 35917

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()))

Upvotes: 8

JBernardo
JBernardo

Reputation: 33397

{i:1.1*j for i,j in my_dict.items()}

Upvotes: 3

Related Questions