更改字典

时间:2015-11-07 14:58:37

标签: python dictionary

如何将字典中的所有值乘以一组数?

dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2

我想将dictionary中的所有值乘以number,以便创建名为dictionary2的第二个字典

创建的字典应如下所示:

dictionary2 = {'one': 2, 'two': 4 'three': 6} 

1 个答案:

答案 0 :(得分:7)

使用词典理解

>>> dictionary = {'one': 1, 'two': 2, 'three': 3}
>>> number = 2
>>> {key:value*number for key,value in dictionary.items()}
{'one': 2, 'three': 6, 'two': 4}

(请注意,顺序与字典本身无序相同)

作为陈述

dictionary2 = {key:value*number for key,value in dictionary.items()}

如果你想要一个简单的版本,你可以使用for循环

dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
dictionary2 = {}

for i in dictionary:
    dictionary2[i] = dictionary[i]*number

print(dictionary2)