列表字典中某个元素的总出现次数
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
将被合并和总计。
我在想类似这样的伪代码:
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
谢谢
您的伪代码是错误的,因为您正在创建一个将键映射到集合的字典,而您实际上想要一个将键映射到将键映射到计数的字典的字典。
以下函数可以满足您的需求:
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], ['Category2', 12], ['Category2', 8]], 'Orange' : [['Category2', 12], ['Category2', 12], '[Category3', 2]]}
我希望输出如下:
d = {'Apple': [['Category1', 14], ['Category2', 20]],'Orange': [['Category2', 24], ['Category3', 2]]}
类别,即具有相同名称的 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
谢谢
您的伪代码是错误的,因为您正在创建一个将键映射到集合的字典,而您实际上想要一个将键映射到将键映射到计数的字典的字典。
以下函数可以满足您的需求:
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