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?
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.
# A nice one liner (edited to remove square brackets) my_dict.update((x, y*2) for x, y in my_dict.items())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With