如何将字典中的所有值乘以一个集合数?
dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
我想将 dictionary 中的所有值乘以 number 以便创建第二个名为 dictionary2 的字典
创建的字典应该是这样的:
dictionary2 = {'one': 2, 'two': 4 'three': 6}
请您参考如下方法:
使用字典理解
>>> 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)
