Eddie
Eddie

Reputation: 63

How can I make a dictionary return keys based on the sum of their values?

I have a list of:

 [['Tameka', '3.5'], ['Esmeralda', '3.9'], ['Katy', '2.7'], ['Lakisha', '3.4'], ['Edwina', '3.0'], ['Darren', '2.9'], ['Rosalinda', '2.8'], ['Margery', '3.1'], ['Kathrine', '3.9'], ['Julio', '4.0'], ['Esmeralda', '4.0'], ['Katy', '3.8'], ['Edwina', '3.2'], ['Darren', '3.8'], ['Rosalinda', '2.9'], ['Margery', '3.2'], ['Kathrine', '3.4'], ['Tameka', '3.6'], ['Julio', '2.0'], ['Katy', '3.0'], ['Lakisha', '4.0'], ['Edwina', '3.7'], ['Darren', '3.7'], ['Rosalinda', '3.8'], ['Margery', '3.5'], ['Kathrine', '2.9'], ['Julio', '3.8'], ['Katy', '4.0'], ['Edwina', '3.6'], ['Darren', '3.8'], ['Rosalinda', '3.7'], ['Margery', '3.9']]

and I'm trying to make it so that keys that repeat sum up their values and then return them like so :

'Tameka', 'Julio', 'Esmeralda', 'Katy', 'Lakisha', 'Edwina', 'Darren', 'Rosalinda', 'Margery', 'Kathrine'

Been stuck on this for a while and I don't know what I'm doing wrong

def dictGpa(cleanList):
    diction = {}
    for item in cleanList:
        if item in diction:
            diction[item] = diction[item.value()]+diction[item.value()]
        else:
            diction[item] = diction[item]

Upvotes: 0

Views: 47

Answers (2)

Daniel Timberlake
Daniel Timberlake

Reputation: 1199

I think it would be cleaner to use defaultdict:

from collections import defaultdict

mydict = defaultdict(lambda: 0)

for x in cleanList:
    mydict[x[0]] += float(x[1])

Upvotes: 1

levi
levi

Reputation: 22697

You have a list of lists, not dicts. so, use item.value() is wrong. it should be item[0] for the key and item[1] for the value.

def dictGpa(cleanList):
        diction = {}
        for item in cleanList:
            if item[0] in diction:
                diction[item[0]] += float(item[1])
            else:
                diction[item[0]]  = float(item[1])

Then in diction you will have a dict where each name has its final sum.

Upvotes: 0

Related Questions