Loop through dictionary and meaning of changes

Say I have a dictionary with names and ratings:

{"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 to do this through all the values ​​in the dictionary?

+4
source share
4 answers

Understanding Dict:

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

You did not ask to replace your dictations with a new one. The following code updates an existing dictionary. It uses basic looping techniques that are just as useful to know as well as understand.

 for name in grade_dict: grade_dict[name] *= 1.1 
+4
source

For python 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() } 
+3
source
 {i:1.1*j for i,j in my_dict.items()} 
+2
source

Source: https://habr.com/ru/post/1384486/


All Articles