9

I have the following two numpy arrays:

a = array([400., 403., 406.]);
b = array([0.2,0.55,0.6]);

Now I would like to create a dictionary where the array a acts as keys and b as corresponding values:

dic = { 
  400: 0.2,
  403: 0.55,
  406: 0.6
}

How could I achieve this ?

1 Answers1

9

You can use a quick for loop with zipped iterables.

import numpy as np
a = np.array([400., 403., 406.]);
b = np.array([0.2,0.55,0.6]);
dict = {}
for A, B in zip(a, b):
    dict[A] = B

print(dict)
# {400.0: 0.2, 403.0: 0.55, 406.0: 0.6}
prince.e
  • 236
  • 2
  • 4
  • 6
    The same using [dict comprehension](https://stackoverflow.com/a/14507637/2641825): `{A: B for A, B in zip(a, b)}` – Paul Rougieux Apr 21 '20 at 05:43
  • 2
    Minor comment on this answer: it is generally bad practice to use reserved type names such as `dict` as variable names. – Colin Oct 03 '21 at 05:41