Reputation: 5261
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
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
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
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