w3resource

How to convert a NumPy array to a Dictionary with Indices as keys?


NumPy: Interoperability Exercise-8 with Solution


Write a NumPy program to convert a NumPy array to a dictionary with indices as keys and array elements as values.

Sample Solution:

Python Code:

import numpy as np

# Create a NumPy array
array = np.array([10, 20, 30, 40, 50])
print("Original NumPy array:",array)
print("Type:",type(array))
# Convert NumPy array to dictionary with indices as keys and elements as values
array_dict = {index: value for index, value in enumerate(array)}
print("\nNumPy array to dictionary with indices as keys and elements as values:")
# Print the resulting dictionary
print(array_dict)
print(type(array_dict))

Output:

Original NumPy array: [10 20 30 40 50]
Type: <class 'numpy.ndarray'>

NumPy array to dictionary with indices as keys and elements as values:
{0: 10, 1: 20, 2: 30, 3: 40, 4: 50}
<class 'dict'>

Explanation:

  • Import NumPy Library: Import the NumPy library to create and manipulate the array.
  • Create NumPy Array: Define a NumPy array with elements you want to convert to a dictionary.
  • Convert to Dictionary: Use a dictionary comprehension with enumerate() to create a dictionary where the indices of the array elements become the keys and the array elements become the values.
  • Print Dictionary: Output the resulting dictionary to verify the conversion.

Python-Numpy Code Editor: