如何将字典中的所有值乘以一组数?
dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
我想将dictionary
中的所有值乘以number
,以便创建名为dictionary2
的第二个字典
创建的字典应如下所示:
dictionary2 = {'one': 2, 'two': 4 'three': 6}
答案 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)