Python:对每个字典值执行操作

use*_*652 26 python dictionary

在python 2.6中,我想对每个字典值执行一个操作,例如,我想为每个字典值乘以2.如何为此任务编写更少的代码?

小智 67

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

  • 在python 3.6中我得到`RuntimeError:字典在迭代过程中改变了大小` (4认同)
  • 这种方法是否优于字典理解(例如 0x90 的答案)? (2认同)

Tri*_*ych 15

# Multiply every value in my_dict by 2
for key in my_dict:    
    my_dict[key] *=  2
Run Code Online (Sandbox Code Playgroud)


Dan*_*olo 5

for key in d:
    d[key] = d[key] * 2
Run Code Online (Sandbox Code Playgroud)


0x9*_*x90 5

更新中的每个键my_dict

my_dict.update({n: 2 * my_dict[n] for n in my_dict.keys()})
Run Code Online (Sandbox Code Playgroud)