w3resource

Convert dictionary to NumPy array and print


NumPy: Interoperability Exercise-7 with Solution


Write a NumPy program to convert a dictionary with numeric values to a NumPy array and print the array.

Sample Solution:

Python Code:

import numpy as np

# Initialize a dictionary with numeric values
data_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

print("Original dictionary with numeric values:",data_dict)
print("Type:",type(data_dict))

# Convert the dictionary values to a NumPy array
numpy_array = np.array(list(data_dict.values()))
print("\nDictionary values to a NumPy array")

# Print the NumPy array
print(numpy_array)
print(type(numpy_array))

Output:

Original dictionary with numeric values: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Type: <class 'dict'>

Dictionary values to a NumPy array
[1 2 3 4 5]
<class 'numpy.ndarray'>

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing a dictionary: A dictionary with numeric values is initialized.
  • Converting to NumPy array: The dictionary values are converted to a NumPy array using np.array() and list().
  • Printing the array: The resulting NumPy array is printed.

Python-Numpy Code Editor: