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:

import numpy as np
from ast import literal_eval
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}
  }"""
t = literal_eval(udict)
print("\nOriginal dictionary:")
print(t)
print("Type: ",type(t))
result_nparra = np.array([[v[j] for j in ['a', 'b', 'c', 'd']] for k, v in t.items()])
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'>

Pictorial Presentation:

NumPy: Convert a Python dictionary to a Numpy ndarray

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]