Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 合计列表字典中元素的出现次数_Python_List_Dictionary_Defaultdict - Fatal编程技术网

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…