1
如何將字典中的所有值乘以集數?更改字典的所有值
dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
我想number
使得第二字典創建一個名爲乘以所有dictionary
值的dictionary2
創建應該是這個樣子的詞典:
dictionary2 = {'one': 2, 'two': 4 'three': 6}
如何將字典中的所有值乘以集數?更改字典的所有值
dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
我想number
使得第二字典創建一個名爲乘以所有dictionary
值的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)