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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Convert dictionary to NumPy array and print.
Next: How to convert a nested Python list to a 2D NumPy array and print it?.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/python-exercises/numpy/convert-a-numpy-array-to-a-dictionary-with-indices-as-keys.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics