Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Dict from array in python

Have:

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

numpy array....

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

want

my_dict = {'a': [1,6,11], 'b': [2,7,12], 'c': [3,7,13], 'd': [5,10,15]}
like image 346
Merlin Avatar asked Mar 20 '12 19:03

Merlin


People also ask

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can you put an array in a dictionary?

A dictionary's item is a value that is unambiguously associated with a unique key and the key is used to retrieve the item. The key can be of any type except a variant or an array (but generally it is a string or still an integer). The item can be of any type: integer, real, string, variant, object and so on.

How do you copy an array to a dictionary in Python?

We use the copy. deepcopy() method to copy dict1 elements in the new dictionary, dict2, After successful copying, we update the new copy and see the changes in the original dictionary, As we can see from the output, any change in dict2 is not reflected in dict1.


2 Answers

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

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

Since array is a NumPy array, you can also use

dict(zip(keys, array.T)))
like image 199
Sven Marnach Avatar answered Oct 11 '22 01:10

Sven Marnach


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 is happening when you zip(*) an object, it's quite a useful trick:

zip(*vals)

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

It looks (and you'll see it another answer) like the transpose! There is a 'gotcha, here. 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)]
like image 28
Hooked Avatar answered Oct 11 '22 01:10

Hooked