Python 合计列表字典中元素的出现次数
我有一本清单字典:Python 合计列表字典中元素的出现次数,python,list,dictionary,defaultdict,Python,List,Dictionary,Defaultdict,我有一本清单字典: d = {'Apple': [['Category1', 14], ['Category2', 12], ['Category2', 8]], 'Orange' : [['Category2', 12], ['Category2', 12], '[Category3', 2]]} 我希望输出如下: d = {'Apple': [['Category1', 14], ['Category2', 20]],'Orange': [['Category2', 24], [
d = {'Apple': [['Category1', 14], ['Category2', 12], ['Category2', 8]], 'Orange' : [['Category2', 12], ['Category2', 12], '[Category3', 2]]}
我希望输出如下:
d = {'Apple': [['Category1', 14], ['Category2', 20]],'Orange': [['Category2', 24], ['Category3', 2]]}
类别,即具有相同名称的类别1、类别2将被合并和合计
我在想一个伪代码,比如:
output = defaultdict(set)
for key, value in d.items():
for item in value:
total += int(value[1])
output[key].add(value[0],total)
total = 0
谢谢您的伪代码是错误的,因为您正在创建一个将键映射到集合的dict,而您确实需要一个将键映射到将键映射到计数的dict的dict 以下函数满足您的要求:
def tally_up(dct):
totals = dict() # Maps keys to dicts of totals
for key, tuples in dct.items():
subtotals = collections.defaultdict(lambda: 0) # Maps keys to counts
for subkey, count in tuples:
subtotals[subkey] += count
totals[key] = dict(subtotals)
return totals
您的代码无法编译-用引号将键括起来:
d={“Apple”:[[“Category1”,14…