w3resource

NumPy: Convert a Python dictionary to a Numpy ndarray

NumPy: Array Object Exercise-167 with Solution

Write a NumPy program to convert a Python dictionary to a Numpy ndarray.

Sample Solution:

Python Code:

# Importing necessary libraries
import numpy as np
from ast import literal_eval

# String representation of a dictionary
udict = """{"column0":{"a":1,"b":0.0,"c":0.0,"d":2.0},
   "column1":{"a":3.0,"b":1,"c":0.0,"d":-1.0},
   "column2":{"a":4,"b":1,"c":5.0,"d":-1.0},
   "column3":{"a":3.0,"b":-1.0,"c":-1.0,"d":-1.0}
  }"""

# Converting the string dictionary to a Python dictionary
t = literal_eval(udict)

# Printing the original dictionary and its type
print("\nOriginal dictionary:")
print(t)
print("Type: ", type(t))

# Creating a 2D NumPy array using dictionary comprehension
result_nparra = np.array([[v[j] for j in ['a', 'b', 'c', 'd']] for k, v in t.items()])

# Printing the generated NumPy array and its type
print("\nndarray:")
print(result_nparra)
print("Type: ", type(result_nparra)) 

Sample Output:

Original dictionary:
{'column0': {'a': 1, 'b': 0.0, 'c': 0.0, 'd': 2.0},
'column1': {'a': 3.0, 'b': 1, 'c': 0.0, 'd': -1.0},
'column2': {'a': 4, 'b': 1, 'c': 5.0, 'd': -1.0},
'column3': {'a': 3.0, 'b': -1.0, 'c': -1.0, 'd': -1.0}}
Type:  <class 'dict'>

ndarray:
[[ 1.  0.  0.  2.]
 [ 3.  1.  0. -1.]
 [ 4.  1.  5. -1.]
 [ 3. -1. -1. -1.]]
Type:  <class 'numpy.ndarray'>

Explanation:

In the above code -

udict is a string containing a nested dictionary, where the keys of the outer dictionary are column names, and the inner dictionaries have keys 'a', 'b', 'c', and 'd' with corresponding values.

t = literal_eval(udict): literal_eval(udict) from the ast module parses the string representation of the dictionary and converts it into an actual dictionary object, which is stored in the variable t.

result_nparra = np.array([[v[j] for j in ['a', 'b', 'c', 'd']] for k, v in t.items()]): The list comprehension [[v[j] for j in ['a', 'b', 'c', 'd']] for k, v in t.items()] extracts the values from the inner dictionaries in the order 'a', 'b', 'c', 'd', and creates a list of lists.

np.array(...) converts the list of lists into a NumPy array, which is stored in the variable result_nparra.

Finally print() function prints the data and type of the NumPy array result_nparra.

Pictorial Presentation:

NumPy: Convert a Python dictionary to a Numpy ndarray

Python-Numpy Code Editor:

Previous: Write a NumPy program to combine last element with first element of two given ndarray with different shapes.
Next: Write a NumPy program to convert Pandas dataframe to Numpy array with headers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-167.php