ecaz
ecaz

Reputation: 33

Sum values that are elements in the same tuple

I'm selecting data from an sqlite database and creating a dictionary using:

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

This gives me a dictionary that prints as:

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

How do you sum values that are elements in the same tuple? I want it to end up as:

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

Upvotes: 1

Views: 904

Answers (4)

idanshmu
idanshmu

Reputation: 5261

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}

Upvotes: 0

venpa
venpa

Reputation: 4318

result on new dict:

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

If you want to update same variable:

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

Upvotes: 1

Irshad Bhat
Irshad Bhat

Reputation: 8709

>>> 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]})

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239513

Lets say, assetTuples looks something like this

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

You can simply iterate and accumulate the values like this

result = {}

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

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

Upvotes: 0

Related Questions