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?
To convert a numpy array to dictionary the following program uses dict(enumerate(array. flatten(), 1)) and this is what it exactly does: array.
Also as expected, the Numpy array performed faster than the dictionary.
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.
you can use dictionary comprehension:
x = {key: np.sum(value) for key, value in dict_.items()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With