Convert a Dictionary to a NumPy Array in Python

In this tutorial, you learn here to Conversion a Dictionary to an Array in Python by NumPy.

Conversion of Dictionary to an Array

First, you need to understand the basics of Python dictionaries, arrays, and the NumPy library.

  • The dictionary store the different variable value in the Key- Value form. The dictionary is a type of mutable data type and we can collect them in the form of ordered, changeable, and not allow duplication.
  • The array is a kind of special variable which is used to store different variables.
  • NumPy is a kind of array which is a form of the Library of Python.

Here, Python provides a simple built-in function to perform this particular task. There are various ways to perform this operation. We call it np.array() as the data to convert this list to an array. In Python, we sometimes need to convert dictionaries to NumPy arrays, and Python provides an efficient way to perform this operation.

We, Convert a dictionary to a NumPy array and produce an array containing the key-value pairs of the dictionary.

In the below example, we convert the dictionary form into a NumPy array in Python(3.8) for example,

        # Convert a Dictionary to a Numpy Array in Python
import numpy as np

my_dict = {"First Name":"John",
            "Last Name":"Klein",
            "Email":"[email protected]",
            "Mobile No.":"+91651961xxxx",
            "Location":"Germany"}


converted_arr = np.array(list(my_dict.items()))
print("Basic Details Form :-")
print(converted_arr)

Output:-

    Basic Details Form :-
[['First Name' 'John']
 ['Last Name' 'Klein']
 ['Email' '[email protected]']
 ['Mobile No.' '+91651961xxxx']
 ['Location' 'Germany']]

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *