作为同一元组中元素的Sum值

时间:2014-12-10 05:19:33

标签: python dictionary sum tuples elements

我正在从sqlite数据库中选择数据并使用以下方法创建字典:

self.cur.execute('''SELECT description,quantity from assetTable''')
    assetTuples = self.cur.fetchall()
    dic = defaultdict(list)
    for k,v in assetTuples:
        dic[k].append(v)

这给了我一个打印为:

的字典
{'asset1': [11, 25], 'asset2': [6, 5], 'asset3': [88, 11]}

如何对同一元组中元素的值求和?我希望它最终成为:

{'asset1': [36], 'asset2': [11], 'asset3': [99]}

4 个答案:

答案 0 :(得分:1)

结果出现在新词典中:

d={'asset1': [11, 25], 'asset2': [6, 5], 'asset3': [88, 11]}
result = {e:[sum(d[e])] for e in d}

如果您想更新相同的变量:

d.update({e:[sum(d[e])] for e in d})

答案 1 :(得分:0)

让我们说,assetTuples看起来像这样

assetTuples = [('asset1', 11), ('asset1', 25), ('asset2', 6), ('asset2', 5), ('asset3', 88), ('asset3', 11)]

您可以简单地迭代并累积像这样的值

result = {}

for k, v in assetTuples:
    result[k] = result.get(k, 0) + v

print(result)
# {'asset2': 11, 'asset1': 36, 'asset3': 99}

答案 2 :(得分:0)

>>> assetTuples=[('asset1',11),('asset1',25),('asset2',11),('asset3',99)]
>>> dic=defaultdict(list)
>>> for k,v in assetTuples:
...     if dic[k]==[]:
...        dic[k]=[v]
...     else:
...        dic[k][0]+=v
... 
>>> dic
defaultdict(<type 'list'>, {'asset2': [11], 'asset3': [99], 'asset1': [36]})

答案 3 :(得分:0)

assetDict = {'asset1': [11, 25], 'asset2': [6, 5], 'asset3': [88, 11]}

for key, value in assetDict.iteritems():
    assetDict[key] = sum(value)

print assetDict
# {'asset2': 11, 'asset1': 36, 'asset3': 99}