Replace values in a dictionary of NumPy arrays and single numbers with sums

Viewed 194

I have a dictionary surnames:

import numpy as np

surnames = {
    'Sophie': np.array([138, 123]), 
    'Marie': np.array([126, 1, 50, 1]), 
    'Maximilian': np.array([111, 74]),
    'Alexander': 87, 
    'Maria': np.array([85, 15, 89, 2]), 
    'Paul': np.array([70, 59]), 
    'Katharina': 69, 
    'Felix': np.array([61, 53]), 
    'Anna': np.array([57, 58]), 
    'Ben': np.array([49, 47])
}

I would like to sum all arrays and save them in the same dictionary so that the sum replaces the array:

{
    'Sophie': 261,
    'Marie': 178,
    'Maximilian': 185,
    'Alexander': 87,
    'Maria': 191,
    'Paul': 129,
    'Katharina': 69,
    'Felix': 114,
    'Anna': 115,
    'Ben': 96
}

I tried this:

new_dict = dict()
for k, v in surnames:
    new_dict.update({k:sum(v)})

I assume this doesn't work because it only sums single values of the same key?

I also tried this:

data = list(surnames.values())
cl_surnames = np.array(data)
cl_surnames = np.sum(cl_surnames, 0)

I understand why this doesn't work either, but what else can I do?

3 Answers

you can use dictionary comprehension:

x = {key: np.sum(value) for key, value in dict_.items()}

You could do this using dict comprehension:

di = {key:np.sum(value) for (key,value) in di.items()}

But fixing the error that was pointed out in the comments would do the job as well.

You can try it:

new_dict = dict()
for k, v in dict_name.items():
    if not isinstance(v, int):
      new_dict[k] = sum(v)
Related