从字典中添加值

时间:2017-08-16 20:28:23

标签: dictionary sum

我创建了一个字典,我想添加字典中每个项目的值。以下是我到目前为止的情况:

import sys
import re
import collections
import numpy as np

dict = {'x':['x',0], 'y':['y',0], 'z':['z',0]}

然后我使用输入文件来计算x,y和z的实例并将它们添加到字典中:

with open(input_file, 'r', encoding='utf-8') as f:
    for line in f:
        words = line.split()
        count_lines += 1
        num_lines += 1
        num_words += len(words)
        title = line
        for key in dict:
            title = line
            if re.search(key, title):
                trusted[key][1]+=1
                title = re.sub(key,dict[key][0],title)
                while re.search(key, title):
                    dict[key][1]+=1
                    title = re.sub(key,dict[key][0],title)
        dict_values = dict.values()
        output_file.write('Dict:', sum(dict_values[1:-1]))

然后我的字典就是:dict = {'x':['x',6], 'y':['y',10], 'z':['z',8]},我想要一起添加6,10和8。

我试过这个有和没有字符串拆分,我已经尝试将和方程式赋给变量并编写变量等。我不断得到“TypeError:不支持的操作数类型为+:'int'和'list'“和”TypeError:'dict_values'对象不是可订阅的“错误消息。

0 个答案:

没有答案