Search code examples
pythonlistdictionarydefaultdict

Totaling occurrences of an element in a dictionary of lists


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


Solution

  • 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