Ways to Convert a Python Dictionary to a NumPy Array
The task of converting a dictionary to a NumPy array involves transforming the dictionary’s key-value pairs into a format suitable for NumPy. In Python, there are different ways to achieve this conversion, depending on the structure and organization of the resulting array.
For example, consider a dictionary d = {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}. By converting this dictionary to a NumPy array, we can obtain a 2D array where each row contains a key-value pair. The output will be <class 'numpy.ndarray'> [[ 0 0][ 1 1] [ 2 8] [ 3 27] [ 4 64] [ 5 125] [ 6 216]] .
Using np.fromiter()
np.fromiter() creates a NumPy array from an iterable. When working with dictionaries, we can flatten the key-value pairs into a sequence using a generator expression and use np.fromiter() to convert them into a 1D array. This 1D array can then be reshaped into a 2D array, where each row corresponds to a key-value pair from the dictionary.
import numpy as np
d = {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}
arr1 = np.fromiter((k for p in d.items() for k in p), dtype=int)
# Reshape the flattened array into a 2D array with 2 columns (key, value)
arr2 = res.reshape(-1, 2)
print(type(arr2), arr2)
Output
<class 'numpy.ndarray'> [[ 0 0] [ 1 1] [ 2 8] [ 3 27] [ 4 64] [ 5 125] [ 6 216]]
Explanation:
- np.fromiter() flattens the dictionary's key-value pairs into a 1D array by iterating through d.items().
- reshape(-1, 2) then converts this 1D array into a 2D array where each row represents a key-value pair with -1 allowing automatic row inference and 2 specifying two elements per row.
Using np.column_stack()
np.column_stack() stacks 1D arrays as columns into a 2D array. To convert a dictionary to a NumPy array, we can extract the keys and values as separate 1D arrays using dict.keys() and dict.values(). These arrays can then be passed to np.column_stack() to create a 2D array where each row represents a key-value pair from the dictionary.
import numpy as np
d = {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}
res = np.column_stack((d.keys(), d.values()))
print(type(res),res)
Output
<class 'numpy.ndarray'> [[dict_keys([0, 1, 2, 3, 4, 5, 6]) dict_values([0, 1, 8, 27, 64, 125, 216])]]
Explanation: np.column_stack() combine the dictionary's keys and values into a 2D array where each row corresponds to a key-value pair.
Using np.array()
np.array() is the most direct method to convert a dictionary to a NumPy array. By converting the dictionary items into a list of tuples using dict.items() and then passing it to np.array(), we can easily create a 2D array where each row represents a key-value pair from the dictionary. This method is simple and efficient for turning a dictionary into a structured 2D NumPy array.
import numpy as np
d = {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}
res = np.array(list(d.items()))
print(type(res),res)
Output
<class 'numpy.ndarray'> [[ 0 0] [ 1 1] [ 2 8] [ 3 27] [ 4 64] [ 5 125] [ 6 216]]
Explanation:
- d.items() returns key-value pairs as tuples and list(d.items()) converts them into a list of tuples .
- np.array() converts the list of tuples into a 2D NumPy array, where each row represents a key-value pair.