使用collections.defaultdict,不需要if-else:
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(, {'Toronto': 34, 'Ottawa': 45})
>>> get_wins_by_category(d, 'sport')
defaultdict(, {'basketball': 31, 'hockey': 48})
>>> get_wins_by_category(d, 'name')
defaultdict(, {'Senators': 45, 'Blues': 21, 'Raptors': 10, 'Leafs': 3})
另一种选择是collections.Counter:
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})