1

Let's say I have a nested dictionary in a dictionary, with that dictionary's value being a list.

How do I add the sum of the values inside the list? For example:

I would like the output to be dict = {one: {"a": 3, "b": 9}....}

dataset = {
  "one" : { "a" : [ 0, 1, 2 ], "b" : [ 2, 3, 4 ] },
  "two" : { "a" : [ 0, 1, 2, 3 ], "b" : [ 0, 1 ] }
}
BunnyHarts
  • 31
  • 2

3 Answers3

1
def transdict(d, func):
    return {*zip(d.keys(), [func(x) for x in d.values()])}

foo = transdict(dataset, lambda x: transdict(x, sum))
oreopot
  • 3,392
  • 2
  • 19
  • 28
Igor Rivin
  • 4,632
  • 2
  • 23
  • 35
1

Try this way of indexing dictionary, and i think this is simpler than other methods mentioned here

dataset = {
    "one": {"a": [0, 1, 2], "b": [2, 3, 4]},
    "two": {"a": [0, 1, 2, 3], "b": [0, 1]}
}

#indexing your dataset by calling name of item and item inside dictionary
index = dataset['one']['a']
index2 = dataset['one']['b']
index3 = dataset['two']['a']
index4 = dataset['two']['b']

#Updating the item to sum of the list 
dataset['one']['a'] = sum(index)
dataset['one']['b'] = sum(index2)
dataset['two']['a'] = sum(index3)
dataset['two']['b'] = sum(index4)

#Printing the dictionary
print(dataset)

Result:

{'one': {'a': 3, 'b': 9}, 'two': {'a': 6, 'b': 1}}
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
0

If you want a nested dictionary comprehension:

summed = {outer_k: {k:sum(v) for k,v in outer_v.items()}  
          for outer_k, outer_v in dataset.items()} 

Result:

In [66]: summed                                         
Out[66]: {'one': {'a': 3, 'b': 9}, 'two': {'a': 6, 'b': 1}}
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223