Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在字典中使用不同数字的多个键值?_Python - Fatal编程技术网

Python 如何在字典中使用不同数字的多个键值?

Python 如何在字典中使用不同数字的多个键值?,python,Python,我正在尝试从字典中提取多个值 example price_list = {'a': 3, 'b': 2, 'c': 5, 'd': 10} 我打字的时候 total=sum(price_list.values()) print("Total sum is ",total) 结果是20 但是现在我想把a乘以3,b乘以5,c乘以2,d乘以3,我想要的输出是59。最简单的方法是什么?您可以像对任何其他变量一样对字典项执行操作: # multiply 'a' by 3 price_list['a']

我正在尝试从字典中提取多个值

example
price_list = {'a': 3, 'b': 2, 'c': 5, 'd': 10}
我打字的时候

total=sum(price_list.values())
print("Total sum is ",total)
结果是20
但是现在我想把a乘以3,b乘以5,c乘以2,d乘以3,我想要的输出是59。最简单的方法是什么?

您可以像对任何其他变量一样对字典项执行操作:

# multiply 'a' by 3
price_list['a'] *= 3

假设您的数字存储在列表中,遍历这些值,然后与所需的数字相乘,如下所示

price_dict = {'a': 3, 'b': 2, 'c': 5, 'd': 10}
numbers_dict = {'a': 3, 'b': 5, 'c': 2, 'd': 3}

result = 0
for key, value in price_dict.items():
    result += numbers_dict[key] * value
print(result)
#59
试试这个:

price_list = {'a': 3, 'b': 2, 'c': 5, 'd': 10} 
numbers = [3,5,2,3] 

for k,n in list(zip(price_list, numbers)): 
    price_list[k] *= n

然后价目表将更改,您可以像计算结果那样使用
sum

所以您想要
'aaabbbbccddd'
?您想要将键乘以一个值吗?不,我想要键的值与数字相乘。我希望a的值是3乘以3得到9,b的值是2乘以5得到10等等。你知道如何通过键访问值吗?你是怎么解决这个问题的?这些数字是从哪里来的?3.5.2.3?只有在Python 3.7+中才能保证字典顺序,因此在早期版本中,您需要将
数字
转换为dict并通过键进行迭代。好主意。固定的使用
sum
(更新):
result=sum(数字\u dict[key]*键的值,价格中的值\u dict.items())