How to convert a dictionary to a matrix or nArray in Python?


In this article, we will show you how to convert a dictionary to a matrix or a NumPy array using the array() function of the NumPy library in python.

It is sometimes necessary to convert a dictionary in Python into a NumPy array, and Python provides an efficient way of doing so. Converting a dictionary to a NumPy array gives an array containing the key-value pairs in the dictionary.

In this section, we will look at examples of converting various types of dictionaries to a NumPy array in Python

  • Converting a Dictionary to a Numpy Array
  • Converting a Nested Dictionary to a Numpy Array
  • Converting a Dictionary with Mixed keys to a Numpy Array

numpy.array() function

It returns a ndarray. The ndarray is an array object that satisfies the given requirements.

To convert a dictionary into a NumPy array, Python has the numpy.array() method, but we must first perform some preliminary work. Follow these three basic steps as a pre-task.

  • First, use dict.items() to get a group of the key-value pairs in the dictionary.
  • Then, having this group as an object, use list(obj) to convert it to a list.
  • Finally, using this list as data, call numpy.array(data) to convert it to an array.

Syntax

numpy.array(object, dtype = None, *, copy = True, order = ‘K’, subok = False, ndmin = 0)

parameters

  • object − this is an array or any object that exposes the array interface.

  • dtype − The array's preferred data type.

  • copy − If true (which is the default), the item is copied. Otherwise, a copy will only be produced if __array__ returns a copy

  • order − It represents the memory layout of the array

  • subok − If true, sub-classes are passed through; otherwise, the returned array is forced to be a base-class array (default)

  • ndmin − Indicates the minimum number of dimensions for the resultant array.

  • Return Value − returns a ndarray(it is an array object that satisfies the specified requirements)

Converting a Dictionary to a Numpy Array

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import the numpy module with an alias name(np).

  • Create a variable to store an input dictionary.

  • Apply the items() function(returns a group of the key-value pairs in the dictionary) on the input dictionary to get all the key-value pairs in the dictionary and create a variable to store it.

  • Use the list() function(returns a list of an iterable), to convert all the key-value pairs of the dictionary to list data type.

  • Use the array() function(returns a ndarray. The ndarray is an array object that satisfies the given requirements) of NumPy module to convert the above list of data to a NumPy array.

  • Print the resultant NumPy array of the input dictionary after conversion.

Example

The following program converts the input dictionary to a NumPy array using the array() function and returns it −

# importing numpy module with an alias name import numpy as np # creating a dictionary inputDict = {1: 'Hello', 2: 'Tutorialspoint', 3: 'python'} # getting all the key-value pairs in the dictionary result_keyvalpairs = inputDict.items() # converting an object to a list list_data = list(result_keyvalpairs) # converting list to an numpy array using numpy array() function numpy_array = np.array(list_data) print("Input Dictionary =",inputDict) # printing the resultant numpy array print("The resultant numpy array:\n", numpy_array)

Output

On executing, the above program will generate the following output

Input Dictionary = {1: 'Hello', 2: 'Tutorialspoint', 3: 'python'}
The resultant numpy array:
 [['1' 'Hello']
 ['2' 'Tutorialspoint']
 ['3' 'python']]

Converting a Nested Dictionary to a Numpy Array

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store an input nested dictionary(dictionary within another dictionary).

  • Use the list() function(returns a list of an iteratable), to convert all the nested key-value pairs of the dictionary to list data type.

  • Use the array() function of NumPy module to convert the above list of data to a NumPy array.

  • Print the resultant NumPy array of the input dictionary after conversion.

Example

The following program converts the nested input dictionary to a NumPy array using the array() function and returns it

# importing NumPy module with an alias name import numpy as np # creating a nested dictionary nestedDictionary = {1: 'Hello', 2: 'Tutorialspoint', 3: {'X': 'This is', 'Y': 'python', 'Z': 'code'}} # getting all the key-value pairs in the dictionary result_keyvalpairs = nestedDictionary.items() # converting an object to a list list_data = list(result_keyvalpairs) # converting list to an array using numpy array() function numpy_array = np.array(list_data) print("Input nested Dictionary = ",nestedDictionary) # printing the resultant numpy array print("\nThe resultant numpy array:\n", numpy_array)

Output

On executing, the above program will generate the following output

Input nested Dictionary =  {1: 'Hello', 2: 'Tutorialspoint', 3: {'X': 'This is', 'Y': 'python', 'Z': 'code'}}

The resultant numpy array:
 [[1 'Hello']
   [2 'Tutorialspoint']
   [3 {'X': 'This is', 'Y': 'python', 'Z': 'code'}]]

Converting a Dictionary with Mixed keys to a Numpy Array

Create an input dictionary with mixed keys such as string, integer, float, list, and so on, and fill it with random values.

Example

The following program converts a dictionary with Mixed keys to a NumPy array using the array() function and returns it −

# importing numpy module with an alias name import numpy as np # creating a dictionary with mixed keys(like string and numbers as keys) nestedDictionary = {'website': 'Tutorialspoint', 10: [2, 5, 8]} # getting all the key-value pairs in the dictionary result_keyvalpairs = nestedDictionary.items() # converting an object to a list list_data = list(result_keyvalpairs) # converting list to an array using numpy array() function numpy_array = np.array(list_data, dtype=object) # printing the resultant numpy array print("The resultant numpy array:\n", numpy_array)

Output

On executing, the above program will generate the following output

The resultant numpy array:
 [['website' 'Tutorialspoint']
   [10 list([2, 5, 8])]]

Conclusion

We learned about the various types of key value pairs in dictionaries and how to convert them to matrices or Numpy Arrays in Python in this article.

Updated on: 12-Oct-2022

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements