How to Convert a Dictionary into a NumPy Array
In this article, we will learn how to convert a Python Dictionary into a numpy array which is more efficient for numerical operations and provides powerful tools for matrix and array manipulations
Key Steps to Convert a Dictionary to a NumPy Array
- Use dict.items(): This returns key-value pairs from the dictionary.
- Convert to a list: Use list() to convert the key-value pairs to a list.
- Convert to a NumPy array: Use numpy.array() to convert the list of pairs into a NumPy array.
Syntax
numpy.array(object, dtype = None, *, copy = True, order = 'K', subok = False, ndmin = 0)
Parameters:
- object: The input array-like object (e.g., list, tuple, dictionary items).
- dtype: Desired data type of the resulting array.
- copy: Whether to copy the data (default is True).
- order: Memory layout order (default is 'K' for default).
- subok: If True, subclasses of ndarray will be passed through (default is False).
- ndmin: Minimum number of dimensions for the resulting array (default is 0).
Returns: ndarray (An array object satisfying the specified requirements).
Let's look at some examples for a better insight.
Example 1: Using np.array()
In this example, we'll convert a simple dictionary with integer keys and string values into a NumPy array.
import numpy as np
dict_data = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
result = dict_data.items()
data = list(result)
np_arr = np.array(data)
print(np_arr)
Output
[['1' 'Geeks'] ['2' 'For'] ['3' 'Geeks']]
Explanation:
- dict.items(): This returns a view of the dictionary's key-value pairs as tuples.
- list(result): Converts the key-value pairs into a list of tuples.
- np.array(data): Converts the list into a NumPy array.
Example 2: Converting a Dictionary with Nested Data
Now, let’s work with a dictionary that has nested data as values (a nested dictionary).
import numpy as np
dict_data = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
res = dict_data.items()
data = list(res)
np_arr = np.array(data)
print(np_arr)
Output
[[1 'Geeks'] [2 'For'] [3 {'A': 'Welcome', 'C': 'Geeks', 'B': 'To'}]]
Explanation:
- Nested dictionary: The value for key 3 is another dictionary, which is included in the conversion.
- np.array(data): The nested dictionary will be treated as a single object within the NumPy array.
Example 3: Converting a Dictionary with Mixed Key Types
In this case, we'll work with a dictionary that has mixed key types: a string and an integer.
import numpy as np
dict_data = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
res = dict_data.items()
data = list(res)
np_arr = np.array(data)
print(np_arr)
Output
[[1 list([1, 2, 3, 4])] ['Name' 'Geeks']]
Explanation:
- Mixed data types: The dictionary has a string key 'Name' and an integer key 1, with values that are a string and a list respectively.
- np.array(data): The list containing both types of values is converted into a NumPy array, maintaining its structure.
Related Article: Python Numpy