python所有值和,python-字典中所有值的总和,其中包含键中的项

给定一个字典和一个字符串作为参数,返回一个新字典,其中包含指定为类别的项(第二个参数,“ 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

我的问题是等号后写什么.我知道,如果不止一次出现该项目,且该项目取包含该项目的所有值的总和,但我不知道如何将其编写为代码.另请注意,三元组将始终按此顺序排列:名称,城市,运动.

解决方法:

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

标签:dictionary,key,python

来源: https://codeday.me/bug/20191122/2059383.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值