0
votes

I have a dictionary of lists as below:

defaultdict(<class 'list'>, {0: [[1.0, 2.0, 3.0], [7.0, 8.0, 9.0]], 1: [[4.0, 5.0, 6.0], [10.0, 11.0, 12.0]]})

I need a dictionary that reduces the dimension by summing the list's value from it such as below

{0: [6.0, 24.0], 1: [15.0, 33.0]}

Hints: 6.0 = [1.0+2.0 +3.0] 24.0 =[7.0+8.0+9.0]

2

2 Answers

1
votes

Iterate over the keys and sum each of the sublists in a list comprehension:

d = {0: [[1.0, 2.0, 3.0], [7.0, 8.0, 9.0]], 1: [[4.0, 5.0, 6.0], [10.0, 11.0, 12.0]]}

for k in d:
    d[k] = [sum(l) for l in d[k]]

>>> d
{0: [6.0, 24.0], 1: [15.0, 33.0]}

Also works on a defaultdict.

A new dictionary can be obtained without modifying the original by using a dictionary comprehension:

new_d = {k:[sum(l) for l in d[k]] for k in d}
0
votes

recursion is an effective way to tranverse and evaluate nested dictionaries

 defaultDict={0: [[1.0, 2.0, 3.0], [7.0, 8.0, 9.0]], 1: [[4.0, 5.0, 6.0], [10.0, 11.0, 12.0]]}

 def walk_the_tree(inputDict,parent_index=None):
     if isinstance(inputDict,dict):
         for key, value in inputDict.items():
             if isinstance(value,list):
                  ret_index,type,result=walk_the_tree(value,key)
                 print(key, ret_index, type, result)
     elif isinstance(inputDict,list):
         sum=0
         for index,alist in enumerate(inputDict):
             #print(index,alist)
             ret_index,type,value=walk_the_tree(alist,index)
             if type=="Sum List":
                 print ("replace value",parent_index, index, value)
                 defaultDict[parent_index][index]=value
             print(type,value)
             if type=="Leaf":
                  sum+=value
        return index,"Sum List",sum
     else:
        return 0,"Leaf", inputDict
    return

  walk_the_tree(defaultDict)

  print(defaultDict)

  output:
  {0: [6.0, 24.0], 1: [15.0, 33.0]}