给定一个字典和一个字符串作为参数,返回一个新字典,其中包含指定为类别的项(第二个参数,“city”、“sport”、“name”之一)作为键及其关联值。如果项的出现次数多于一次,则取这些值的总和。
前任。

>>> get_wins_by_category(d, 'city')
{'Toronto': 34, 'Ottawa': 45}
>>> get_wins_by_category(d, 'sport')
{'basketball': 31, 'hockey': 48}
>>> get_wins_by_category(d, 'name')
{'Raptors': 10, 'Blues': 21, 'Senators': 45, 'Leafs': 3}

到目前为止我得到的:
d = {('Raptors', 'Toronto', 'basketball'): 10,
     ('Blues', 'Toronto', 'basketball'): 21,
     ('Senators', 'Ottawa', 'hockey'): 45,
     ('Leafs', 'Toronto', 'hockey'): 3}

def get_wins_by_category(dct, category):
    new_dict = {}
    if category == 'city':
        for key in dct.keys():
            new_dict[key[1]] = #todo
    elif category == 'sport':
        for key in dct.keys():
            new_dict[key[2]] = #todo
    elif category == 'name':
        for key in dct.keys():
            new_dict[key[0]] = #todo
    return new_dict

我的问题是等号后面写什么。我知道,如果该项的出现次数不止一次,则取包含该项的所有值之和,但我不知道如何将其编写为代码。还有一点要注意的是,三元组的顺序永远是:name,city,sport。

最佳答案

使用collections.defaultdict,如果需要,则不使用:

from collections import defaultdict
def get_wins_by_category(team_to_win, category):

    d = {'name':0, 'city':1, 'sport':2}
    dic = defaultdict(int)
    for k, v in team_to_win.items():
        dic[k[d[category]]] += v
    return dic
...
>>> get_wins_by_category(d, 'city')
defaultdict(<type 'int'>, {'Toronto': 34, 'Ottawa': 45})
>>> get_wins_by_category(d, 'sport')
defaultdict(<type 'int'>, {'basketball': 31, 'hockey': 48})
>>> get_wins_by_category(d, 'name')
defaultdict(<type 'int'>, {'Senators': 45, 'Blues': 21, 'Raptors': 10, 'Leafs': 3})

另一种选择是:
from collections import Counter
def get_wins_by_category(team_to_win, category):
    #index each category points to
    d = {'name':0, 'city':1, 'sport':2}
    dic = Counter()
    for k, v in team_to_win.items():
        dic[k[d[category]]] += v
    return dic
...
>>> get_wins_by_category(d, 'city')
Counter({'Ottawa': 45, 'Toronto': 34})
>>> get_wins_by_category(d, 'sport')
Counter({'hockey': 48, 'basketball': 31})
>>> get_wins_by_category(d, 'name')
Counter({'Senators': 45, 'Blues': 21, 'Raptors': 10, 'Leafs': 3})

关于python - 包含键中项的字典中所有值的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20481552/

10-09 19:07