w3resource

Convert dictionary to NumPy array and print


7. Dictionary to Array Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a dictionary with unsorted numeric values into a sorted NumPy array based on keys.
  • Write a Numpy program to convert a nested dictionary with numeric values into a multidimensional NumPy array while handling missing keys.
  • Write a Numpy program to convert a dictionary with mixed numeric types to a NumPy array and enforce a common numeric type using casting.
  • Write a Numpy program to convert a dictionary with values as lists into a 2D NumPy array and validate the dimensions against the keys.

Go to:


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

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.