列表字典中元素的总计出现次数(Totaling occurrences of an element in a dictionary of lists)

编程入门 行业动态 更新时间:2024-10-26 10:32:53
列表字典中元素的总计出现次数(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 = 0

Thanks

最满意答案

您的伪代码是错误的,因为您正在创建一个将密钥映射到集合的字典,而您确实需要一个将密钥映射到将密钥映射到计数的字符串的字典。

以下功能可以满足您的需求:

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

Your 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

更多推荐

本文发布于:2023-07-16 07:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1125423.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   元素   次数   列表   Totaling

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!