Skip to content
Related Articles

Related Articles

How to convert NumPy array to dictionary in Python?
  • Last Updated : 11 Oct, 2020
GeeksforGeeks - Summer Carnival Banner

The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.

Approach

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

  • array.flatten: This function is used to get a copy of given array, collapsed into one dimension.
  • enumerate: Enumerate method comes with an automatic counter/index for each of the items present in the list. The first index value will start from 0
  • dict: this function is used to convert any object to dictionary.

Example 1:

Python3




# importing required librariess
import numpy as np
  
# creating a numpy array
array = np.array([['a', 'b', 'c'],
                  ['d', 'e', 'f'],
                  ['g', 'h', 'i']])
  
# convert nympy array to dictionary
d = dict(enumerate(array.flatten(), 1))
  
# print numpy array
print(array)
print(type(array))
  
# print dictionary
print(d)
print(type(d))

Output:

[[‘a’ ‘b’ ‘c’]



[‘d’ ‘e’ ‘f’]

[‘g’ ‘h’ ‘i’]]

<class ‘numpy.ndarray’>

{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’, 5: ‘e’, 6: ‘f’, 7: ‘g’, 8: ‘h’, 9: ‘i’}

<class ‘dict’>

Example 2:

Python3




# importing required librariess
import numpy as np
  
# creating a numpy array
array = np.array([['1', '2', '3','4','5'],
                  ['6', '7', '8','9','10'],
                  ['11', '12', '13','14','15']])
  
# convert nympy array to dictionary
d = dict(enumerate(array.flatten(), 1))
  
# print numpy array
print(array)
print(type(array))
  
# print dictionary
print(d)
print(type(d))

Output:



[[‘1’ ‘2’ ‘3’ ‘4’ ‘5’]

[‘6’ ‘7’ ‘8’ ‘9’ ’10’]

[’11’ ’12’ ’13’ ’14’ ’15’]]

<class ‘numpy.ndarray’>

{1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’, 5: ‘5’, 6: ‘6’, 7: ‘7’, 8: ‘8’, 9: ‘9’, 10: ’10’, 11: ’11’, 12: ’12’, 13: ’13’, 14: ’14’, 15: ’15’}

<class ‘dict’>

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :