列表字典中元素的总计出现次数(Totaling occurrences of an element in a dictionary of lists)
我有这个列表字典:
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]]}类别即Category1, Category2具有相同名称的Category1, Category2将被合并并合计。
我在想一个类似的伪代码:
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谢谢
I have this dictionary of lists:
d = {'Apple': [['Category1', 14], ['Category2', 12], ['Category2', 8]], 'Orange' : [['Category2', 12], ['Category2', 12], '[Category3', 2]]}I would like the output to be like:
d = {'Apple': [['Category1', 14], ['Category2', 20]],'Orange': [['Category2', 24], ['Category3', 2]]}Category i.e Category1, Category2 with the same name will be combined and totaled.
I was thinking of a pseudocode of something like:
output = defaultdict(set) for key, value in d.items(): for item in value: total += int(value[1]) output[key].add(value[0],total) total = 0Thanks
最满意答案
您的伪代码是错误的,因为您正在创建一个将密钥映射到集合的字典,而您确实需要一个将密钥映射到将密钥映射到计数的字符串的字典。
以下功能可以满足您的需求:
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 totalsYour pseudocode is wrong because you're creating a dict that maps keys to sets whereas you really want a dict that maps keys to dicts that maps keys to counts.
The following function does what you want:
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更多推荐
发布评论