Reputation: 617
How can I multiply all of the values in a dictionary by a set number?
dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
I want to multiply all of the values in dictionary
by number
so that a second dictionary is created called dictionary2
The dictionary created should look something like this:
dictionary2 = {'one': 2, 'two': 4 'three': 6}
Upvotes: 1
Views: 72
Reputation: 52071
Use a dictionary comprehension
>>> dictionary = {'one': 1, 'two': 2, 'three': 3}
>>> number = 2
>>> {key:value*number for key,value in dictionary.items()}
{'one': 2, 'three': 6, 'two': 4}
(Note that the order is not the same as dictionaries are inherently unordered)
As a statement
dictionary2 = {key:value*number for key,value in dictionary.items()}
If you want a trivial version you can use a for loop
dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
dictionary2 = {}
for i in dictionary:
dictionary2[i] = dictionary[i]*number
print(dictionary2)
Upvotes: 7