2015-11-07 84 views
1

如何将字典中的所有值乘以集数?更改字典的所有值

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

我想number使得第二字典创建一个名为乘以所有dictionary值的dictionary2

创建应该是这个样子的词典:

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

回答

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)