dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
如何在python3中对key1的值求和,如果这些值是list的格式。
在字典[key]上使用sum(),例如
dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
r = sum(dict1['Key1'])
print(r)
>> 294
或者如果你想对字典的第一个键求和,不一定是'Key1'那么你可以在循环中完成
dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
for _, val_list in dict1.items(): # loop over list
r = sum(val_list) # sum the list
break
print(r)
>> 294