开发者

Python: Perform an operation on each dictionary value

开发者 https://www.devze.com 2023-02-11 05:06 出处:网络
In python 2.6 I want to perform an ope开发者_如何转开发ration on each dictionary value, for example, I want to multiply by 2 for each of them. How to code less for this task? # A nice one liner (edite

In python 2.6 I want to perform an ope开发者_如何转开发ration on each dictionary value, for example, I want to multiply by 2 for each of them. How to code less for this task?


# A nice one liner (edited to remove square brackets)   
my_dict.update((x, y*2) for x, y in my_dict.items())


# Multiply every value in my_dict by 2
for key in my_dict:    
    my_dict[key] *=  2


update each key in my_dict:

my_dict.update({n: 2 * my_dict[n] for n in my_dict.keys()})


for key in d:
    d[key] = d[key] * 2
0

精彩评论

暂无评论...
验证码 换一张
取 消