To convert a dictionary to a NumPy array in Python, you can use the numpy.array() method.
Follow these steps:
- Step 1: Use dict.items() method to get a key-value pair view object.
- Step 2: Use the list() method to convert the view object into a list.
- Step 3: Use the numpy.array() to convert this list into an array.
Visual Representation
Example 1
import numpy as np
# Define a dictionary with player numbers and names
player_dict = {
7: "Ronaldo",
10: "Messi",
11: "Neymar",
}
print("=== Before Conversion ===", player_dict)
print(type(player_dict))
# Retrieve dictionary items (key-value pairs)
dict_items = player_dict.items()
# Convert the items to a list
items_list = list(dict_items)
# Convert the list to a NumPy array
players_array = np.array(items_list)
# Print the NumPy array
print("=== After Conversion ===", players_array)
print(type(players_array))
Output
=== Before Conversion ===
{7: 'Ronaldo', 10: 'Messi', 11: 'Neymar'}
<class 'dict'>
=== After Conversion ===
[['7' 'Ronaldo']
['10' 'Messi']
['11' 'Neymar']]
<class 'numpy.ndarray'>
Example 2: Using Nested Dictionary
Visual Representation
import numpy as np
# Define a nested dictionary with player numbers, names, and additional info
player_dict = {
7: "Ronaldo",
10: "Messi",
11: {"name": "Neymar", "team": "Al Hilal", "nationality": "Brazil"}
}
print("=== Before Conversion ===", player_dict)
print(type(player_dict))
# Retrieve dictionary items (key-value pairs)
dict_items = player_dict.items()
# Convert the items to a list
items_list = list(dict_items)
# Convert the list to a NumPy array
players_array = np.array(items_list)
# Print the NumPy array
print("=== After Conversion ===", players_array)
print(type(players_array))
Output
=== Before Conversion ===
{7: 'Ronaldo', 10: 'Messi', 11: {'name': 'Neymar', 'team': 'Al Hilal', 'nationality': 'Brazil'}}
<class 'dict'>
=== After Conversion ===
[[7 'Ronaldo']
[10 'Messi']
[11 {'name': 'Neymar', 'team': 'Al Hilal', 'nationality': 'Brazil'}]]
<class 'numpy.ndarray'>
Hello
—————————————————————————
TypeError Traceback (most recent call last)
in
82 }
83 data = categories.items()
—> 84 list = list(data)
85 arr = np.array(list)
86 print(arr)
TypeError: ‘list’ object is not callable
Krunal
To resolve this issue, I would recommend that you rename your ‘list’ variable to avoid conflicts with built-in Python functions.
Please refer to the modified example above for guidance.