Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Convert a Dictionary into a NumPy Array?
Python's NumPy library provides powerful tools for working with structured data. When dealing with dictionary data, you may need to convert it to NumPy arrays for mathematical operations and data analysis.
This tutorial will show you how to convert both simple and nested dictionaries into NumPy arrays using various methods.
Converting a Simple Dictionary
Let's start by converting a basic dictionary with key-value pairs −
import numpy as np
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Convert dictionary items to NumPy array
my_array = np.array(list(my_dict.items()))
print("Dictionary items as array:")
print(my_array)
print(f"Array shape: {my_array.shape}")
print(f"Data type: {my_array.dtype}")
Dictionary items as array: [['a' '1'] ['b' '2'] ['c' '3'] ['d' '4']] Array shape: (4, 2) Data type: <U21
Converting Only Values
If you only need the values from the dictionary −
import numpy as np
my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
# Convert only values to NumPy array
values_array = np.array(list(my_dict.values()))
print("Values as array:")
print(values_array)
# Convert only keys to NumPy array
keys_array = np.array(list(my_dict.keys()))
print("Keys as array:")
print(keys_array)
Values as array: [10 20 30 40] Keys as array: ['a' 'b' 'c' 'd']
Converting Nested Dictionaries
For nested dictionaries, we can extract values at different levels −
import numpy as np
nested_dict = {
"row1": [1, 2, 3],
"row2": [4, 5, 6],
"row3": [7, 8, 9]
}
# Convert nested dictionary values to 2D array
nested_array = np.array(list(nested_dict.values()))
print("Nested dictionary as 2D array:")
print(nested_array)
print(f"Shape: {nested_array.shape}")
Nested dictionary as 2D array: [[1 2 3] [4 5 6] [7 8 9]] Shape: (3, 3)
Complex Nested Structure
import numpy as np
complex_dict = {
"students": {"math": [85, 90, 78], "science": [92, 88, 95]},
"teachers": {"math": [1, 2], "science": [3, 4]}
}
# Extract specific nested values
math_scores = np.array(complex_dict["students"]["math"])
science_scores = np.array(complex_dict["students"]["science"])
print("Math scores:", math_scores)
print("Science scores:", science_scores)
# Combine into 2D array
all_scores = np.array([math_scores, science_scores])
print("Combined scores:")
print(all_scores)
Math scores: [85 90 78] Science scores: [92 88 95] Combined scores: [[85 90 78] [92 88 95]]
Method Comparison
| Method | Use Case | Result Type |
|---|---|---|
np.array(list(dict.items())) |
Key-value pairs | 2D array (mixed types) |
np.array(list(dict.values())) |
Values only | 1D/2D array (same types) |
np.array(list(dict.keys())) |
Keys only | 1D array (strings) |
Accessing Array Elements
Once converted, you can access elements using standard NumPy indexing −
import numpy as np
data_dict = {'x': [1, 2], 'y': [3, 4], 'z': [5, 6]}
data_array = np.array(list(data_dict.values()))
print("Full array:")
print(data_array)
print("\nFirst row:", data_array[0])
print("Element at [1,1]:", data_array[1, 1])
print("Last column:", data_array[:, -1])
Full array: [[1 2] [3 4] [5 6]] First row: [1 2] Element at [1,1]: 4 Last column: [2 4 6]
Conclusion
Converting dictionaries to NumPy arrays enables efficient mathematical operations and data manipulation. Use dict.values() for numerical data and dict.items() when you need both keys and values preserved in the array structure.
