Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Perform an operation on each dictionary value

In python 2.6 I want to perform an operation on each dictionary value, for example, I want to multiply by 2 for each of them. How to code less for this task?

like image 905
user469652 Avatar asked Feb 15 '11 22:02

user469652


People also ask

How do you perform operations on dictionary values?

In this we simply run a loop to traverse each key in dictionary and perform the desired operation. An alternate one-liner to perform this task, the combination of above functions can be used to perform this particular task. The update function is used to perform the necessary operation over the dictionary.


1 Answers

# A nice one liner (edited to remove square brackets)    my_dict.update((x, y*2) for x, y in my_dict.items()) 
like image 196
Reuben Cummings Avatar answered Sep 24 '22 15:09

Reuben Cummings