w3resource

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


8. Array to Dictionary Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a 1D NumPy array into a dictionary with indices as keys and square the elements as values.
  • Write a Numpy program to convert a 2D NumPy array into a dictionary where each key is a tuple representing row and column indices.
  • Write a Numpy program to convert a NumPy array into a dictionary and then filter out entries that do not meet a specified condition.
  • Write a Numpy program to convert a flattened NumPy array into a dictionary mapping index ranges to subarray slices.

Go to:


Previous: Convert dictionary to NumPy array and print.
Next: How to convert a nested Python list to a 2D NumPy array and print it?.

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.