How to create a dict from an array in python

There is:

keys = ['a', 'b','c','d'] 

numpy array ....

 array = numpy.array([[1, 2, 3, 5], [6, 7, 8, 10], [11, 12, 13, 15]]) 

want to

 my_dict = {'a': [1,6,11], 'b': [2,7,12], 'c': [3,7,13], 'd': [5,10,15]} 
+4
source share
2 answers

Move the array, zip() keys with the result and convert to dict :

 dict(zip(keys, zip(*array))) 

Since array is a NumPy array, you can also use

 dict(zip(keys, array.T))) 
+14
source
 keys = ['a', 'b','c','d'] vals = [[1, 2, 3, 5], [6, 7, 8, 10], [11, 12, 13, 15]] dict(zip(keys, zip(*vals))) {'a': (1, 6, 11), 'c': (3, 8, 13), 'b': (2, 7, 12), 'd': (5, 10, 15)} 

It’s useful to see what happens when you zip(*) an object, this is a pretty useful trick:

 zip(*vals) [(1, 6, 11), (2, 7, 12), (3, 8, 13), (5, 10, 15)] 

It looks (and you will see another answer), like transposition! There is a "gotcha". If one of the lists is shorter than the others, zip(*) will stop prematurely:

  vals = [[1, 2, 3, 5], [6, 7, 8, 10], [11, 12, 13]] zip(*vals) [(1, 6, 11), (2, 7, 12), (3, 8, 13)] 
+6
source

Source: https://habr.com/ru/post/1402524/


All Articles