The Wayback Machine - https://web.archive.org/web/20240606161602/https://www.geeksforgeeks.org/how-to-convert-numpy-array-to-dictionary-in-python/
Open In App

How to convert NumPy array to dictionary in Python?

Last Updated : 26 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 libraries
import numpy as np
 
# creating a numpy array
array = np.array([['a', 'b', 'c'],
                  ['d', 'e', 'f'],
                  ['g', 'h', 'i']])
 
# convert numpy 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’>

Time Complexity: The time complexity for converting a numpy array to a dictionary is O(n), where n is the number of elements in the numpy array.

Space Complexity: The space complexity for converting a numpy array to a dictionary is O(n), where n is the number of elements in the numpy array.

Example 2:

Python3




# importing required libraries
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 numpy 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’>

Time complexity: O(n), where n is the number of elements in the numpy array.

Auxiliary space: O(n), where n is the number of elements in the numpy array, due to the creation of the dictionary.



Similar Reads

Different ways to convert a Python dictionary to a NumPy array
In this article, we will see Different ways to convert a python dictionary into a Numpy array using NumPy library. It’s sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs of t
3 min read
How to convert a dictionary into a NumPy array?
It's sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a dictionary into NumPy array but before applying th
3 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List
The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print(gfg.tolist()) Output[1, 2, 3, 4, 5] SyntaxSynt
1 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.argsort() functionUsing np.lexsort() functionUsing s
4 min read
Creating Series from list, dictionary, and numpy array in Pandas
Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called index. Pandas Series is nothing but a column in an excel sheet. In this article, we will see various ways of creating a series using different data types. Creating Series from l
2 min read
Difference between Numpy array and Numpy matrix
While working with Python many times we come across the question that what exactly is the difference between a numpy array and numpy matrix, in this article we are going to read about the same. What is np.array() in PythonThe Numpy array object in Numpy is called ndarray. We can create ndarray using numpy.array() function. It is used to convert a l
3 min read
Article Tags :
Practice Tags :