Related Articles
Different ways to convert a Python dictionary to a NumPy array
• Last Updated : 02 Sep, 2020

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 the dictionary.

Let’s see the different methods:

Method 1: Using numpy.array() and List Comprehension together.

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

Return: An array object satisfying the specified requirements.

We have used np.array() to convert a dictionary to nd array. And to get each and every value of dictionary as a list for the input to the np.array(), concept of List comprehension is used.

Example:

## Python3

 `# importing required librariess``import` `numpy as np``from` `ast ``import` `literal_eval`` ` `# creating class of string``name_list ``=` `"""{``   ``"column0": {"First_Name": "Akash",``   ``"Second_Name": "kumar", "Interest": "Coding"},``                 ` `   ``"column1": {"First_Name": "Ayush",``   ``"Second_Name": "Sharma", "Interest": "Cricket"},``    ` `   ``"column2": {"First_Name": "Diksha",``   ``"Second_Name": "Sharma","Interest": "Reading"},``    ` `   ``"column3": {"First_Name":" Priyanka",``   ``"Second_Name": "Kumari", "Interest": "Dancing"}``    ` `  ``}"""``print``(``"Type of name_list created:\n"``,``      ``type``(name_list))`` ` `# converting string type to dictionary``t ``=` `literal_eval(name_list)`` ` `# printing the original dictionary``print``(``"\nPrinting the original Name_list dictionary:\n"``,``      ``t)`` ` `print``(``"Type of original dictionary:\n"``,``      ``type``(t))`` ` `# converting dictionary to numpy array``result_nparra ``=` `np.array([[v[j] ``for` `j ``in` `[``'First_Name'``, ``'Second_Name'``,``                                          ``'Interest'``]] ``for` `k, v ``in` `t.items()])`` ` `print``(``"\nConverted ndarray from the Original dictionary:\n"``,``      ``result_nparra)`` ` `# printing the type of converted array``print``(``"Type:\n"``, ``type``(result_nparra))`

Output:

Type of name_list created:
<class ‘str’>

Printing the original Name_list dictionary:
{‘column0’: {‘First_Name’: ‘Akash’, ‘Second_Name’: ‘kumar’, ‘Interest’: ‘Coding’},
‘column1’: {‘First_Name’: ‘Ayush’, ‘Second_Name’: ‘Sharma’, ‘Interest’: ‘Cricket’},
‘column2’: {‘First_Name’: ‘Diksha’, ‘Second_Name’: ‘Sharma’, ‘Interest’: ‘Reading’},
‘column3’: {‘First_Name’: ‘ Priyanka’, ‘Second_Name’: ‘Kumari’, ‘Interest’: ‘Dancing’}}
Type of original dictionary:
<class ‘dict’>

Converted ndarray from the Original dictionary:
[[‘Akash’ ‘kumar’ ‘Coding’]
[‘Ayush’ ‘Sharma’ ‘Cricket’]
[‘Diksha’ ‘Sharma’ ‘Reading’]
[‘ Priyanka’ ‘Kumari’ ‘Dancing’]]
Type:
<class ‘numpy.ndarray’>

Method 2: Using numpy.array() and dictionary_obj.items().

We have used np.array() to convert a dictionary to nd array. And to get each and every value of dictionary as a list for the input to the np.array() method, dictionary_obj.items() is used.

Example:

## Python3

 `# importing library``import` `numpy as np`` ` `# creating dictionary as key as ``# a number and value as its cube``dict_created ``=` `{``0``: ``0``, ``1``: ``1``, ``2``: ``8``, ``3``: ``27``,``                ``4``: ``64``, ``5``: ``125``, ``6``: ``216``}`` ` `# printing type of dictionary created``print``(``type``(dict_created))`` ` `# converting dictionary to ``# numpy array ``res_array ``=` `np.array(``list``(dict_created.items()))`` ` `# printing the converted array``print``(res_array)`` ` `# printing type of converted array``print``(``type``(res_array))`

Output:

```<class 'dict'>
[[  0   0]
[  1   1]
[  2   8]
[  3  27]
[  4  64]
[  5 125]
[  6 216]]
<class 'numpy.ndarray'>
```

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