Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 372
mn_wy Avatar asked May 23 '20 11:05

mn_wy


People also ask

Can I store a NumPy array in a dictionary?

To convert a numpy array to dictionary the following program uses dict(enumerate(array. flatten(), 1)) and this is what it exactly does: array.

Is NumPy array faster than dictionary?

Also as expected, the Numpy array performed faster than the dictionary.

Can NumPy arrays be modified?

Reshape. There are different ways to change the dimension of an array. Reshape function is commonly used to modify the shape and thus the dimension of an array.


1 Answers

you can use dictionary comprehension:

x = {key: np.sum(value) for key, value in dict_.items()}
like image 150
Hozayfa El Rifai Avatar answered Oct 30 '22 21:10

Hozayfa El Rifai