Ways to Convert a Python Dictionary to a NumPy Array
Last Updated :
01 Feb, 2025
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.
Python
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.
Python
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.
Python
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.
Similar Reads
How to convert NumPy array to dictionary in Python? The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers givi
3 min read
How to convert a dictionary into a NumPy array? It's sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs in the dictionary. Python provides numpy.array() method to convert a
3 min read
Convert Python List to numpy Arrays NumPy arrays are more efficient than Python lists, especially for numerical operations on large datasets. NumPy provides two methods for converting a list into an array using numpy.array() and numpy.asarray(). In this article, we'll explore these two methods with examples for converting a list into
4 min read
Different Ways to Create Numpy Arrays in Python Creating NumPy arrays is a fundamental aspect of working with numerical data in Python. NumPy provides various methods to create arrays efficiently, catering to different needs and scenarios. In this article, we will see how we can create NumPy arrays using different ways and methods. Ways to Create
3 min read
Ways to convert string to dictionary To convert a String into a dictionary, the stored string must be in such a way that a key: value pair can be generated from it. For example, a string like "{'a': 1, 'b': 2, 'c': 3}" or "a:1, b:10" can be converted into a dictionary This article explores various methods to perform this conversion eff
2 min read
How To Convert Python Dictionary To JSON? In Python, a dictionary stores information using key-value pairs. But if we want to save this data to a file, share it with others, or send it over the internet then we need to convert it into a format that computers can easily understand. JSON (JavaScript Object Notation) is a simple format used fo
6 min read
Python - Convert an array to an ordinary list with the same items In Python, we often work with different array-like structures such as arrays, NumPy arrays, or regular lists. Sometimes, we need to convert these arrays to a simple Python list for easier manipulation or compatibility with other functions. Using list() constructorlist() function is the most straight
2 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example Python3 import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print
1 min read
Ways to create a dictionary of Lists - Python A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key.Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
How to Convert NumPy Matrix to Array In NumPy, a matrix is essentially a two-dimensional NumPy array with a special subclass. In this article, we will see how we can convert NumPy Matrix to Array. Also, we will see different ways to convert NumPy Matrix to Array. Convert Python NumPy Matrix to an ArrayBelow are the ways by which we can
3 min read