如何根据值的总和使字典返回键?

时间:2015-02-19 02:11:51

标签: python list dictionary

我有一个清单:

 [['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']]

我正试图让它重复总结它们的值,然后像这样返回它们:

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

被困在这一段时间,我不知道我做错了什么

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]

2 个答案:

答案 0 :(得分:1)

我认为使用defaultdict

会更干净
from collections import defaultdict

mydict = defaultdict(lambda: 0)

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

答案 1 :(得分:0)

你有一个列表列表,而不是dicts。所以,使用item.value()是错误的。密钥应为item[0],值为item[1]

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

然后在diction中你将得到一个字典,其中每个名字都有其最终总和。