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:

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

Previous: Convert NumPy array to Pandas DataFrame and print.
Next: How to convert a NumPy array to a Dictionary with Indices as keys?

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/convert-dictionary-to-numpy-array-and-print.php