Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of only couple of indexes of lists in a dictionary

If I have this type of dictionary:

a_dictionary = {"dog": [["white", 3, 5], ["black", 6,7], ["Brown", 23,1]],
                "cat": [["gray", 5, 6], ["brown", 4,9]],
                "bird": [["blue", 3,5], ["green", 1,2], ["yellow", 4,9]],
                "mouse": [["gray", 3,4]]
                }

And I would like to sum from first line 3 with 6 and 23 and on next line 5 with 4 on so on so I will have when printing:

dog [32, 13]
cat [9, 15]
bird [8, 16]
mouse [3,4]

I tried a for loop of range of a_dictionary to sum up by index, but then I can't access the values by keys like: a_dictionary[key]

But if I loop through a_dictionary like for key, value in a dictionary.items():, I can't access it by index to sum up the needed values.

I would love to see how this could be approached. Thanks.

like image 829
Erika Avatar asked Dec 21 '25 02:12

Erika


1 Answers

Generally, in Python you don't want to use indices to access values in lists or other iterables (of course this cannot be always applicable).

With clever use of zip() and map() you can sum appropriate values:

a_dictionary = {
    "dog": [["white", 3, 5], ["black", 6, 7], ["Brown", 23, 1]],
    "cat": [["gray", 5, 6], ["brown", 4, 9]],
    "bird": [["blue", 3, 5], ["green", 1, 2], ["yellow", 4, 9]],
    "mouse": [["gray", 3, 4]],
}

for k, v in a_dictionary.items():
    print(k, list(map(sum, zip(*(t for _, *t in v)))))

Prints:

dog [32, 13]
cat [9, 15]
bird [8, 16]
mouse [3, 4]

EDIT:

  1. With (t for _, *t in v) I'll extract the last two values from the lists (discarding the first string value)

    [3, 5], [6, 7], [23, 1]
    [5, 6], [4, 9]
    [3, 5], [1, 2], [4, 9]
    [3, 4]
    
  2. zip(*...) is a transposing operation

    (3, 6, 23), (5, 7, 1)
    (5, 4), (6, 9)
    (3, 1, 4), (5, 2, 9)
    (3,), (4,)
    
  3. Then I apply sum() on each of the sublist created in step 2. with map()

    32, 13
    9, 15
    8, 16
    3, 4
    
  4. The result of the map() is stored into a list

like image 186
Andrej Kesely Avatar answered Dec 23 '25 16:12

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!