Python: Perform an operation on each dictionary value

Question:

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?

Asked By: user469652

||

Answers:

# Multiply every value in my_dict by 2
for key in my_dict:    
    my_dict[key] *=  2
Answered By: Kenan Banks
for key in d:
    d[key] = d[key] * 2
Answered By: Daniel DiPaolo

update each key in my_dict:

my_dict.update({n: 2 * my_dict[n] for n in my_dict.keys()})
Answered By: 0x90
# A nice one liner (edited to remove square brackets)   
my_dict.update((x, y*2) for x, y in my_dict.items())
Answered By: Reuben Cummings
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.