You could use np.array(list(result.items()), dtype=dtype):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = ['id','data']
formats = ['f8','f8']
dtype = dict(names = names, formats=formats)
array = np.array(list(result.items()), dtype=dtype)

print(repr(array))

yields

array([(0.0, 1.1181753789488595), (1.0, 0.5566080288678394),
       (2.0, 0.4718269778030734), (3.0, 0.48716683119447185), (4.0, 1.0),
       (5.0, 0.1395076201641266), (6.0, 0.20941558441558442)], 
      dtype=[('id', '<f8'), ('data', '<f8')])

If you don't want to create the intermediate list of tuples, list(result.items()), then you could instead use np.fromiter:

In Python2:

array = np.fromiter(result.iteritems(), dtype=dtype, count=len(result))

In Python3:

array = np.fromiter(result.items(), dtype=dtype, count=len(result))

Why using the list [key,val] does not work:

By the way, your attempt,

numpy.array([[key,val] for (key,val) in result.iteritems()],dtype)

was very close to working. If you change the list [key, val] to the tuple (key, val), then it would have worked. Of course,

numpy.array([(key,val) for (key,val) in result.iteritems()], dtype)

is the same thing as

numpy.array(result.items(), dtype)

in Python2, or

numpy.array(list(result.items()), dtype)

in Python3.


np.array treats lists differently than tuples: Robert Kern explains:

As a rule, tuples are considered "scalar" records and lists are recursed upon. This rule helps numpy.array() figure out which sequences are records and which are other sequences to be recursed upon; i.e. which sequences create another dimension and which are the atomic elements.

Since (0.0, 1.1181753789488595) is considered one of those atomic elements, it should be a tuple, not a list.

Answer from unutbu on Stack Overflow
🌐
NumPy
numpy.org › doc › stable › user › basics.rec.html
Structured arrays — NumPy v2.5 Manual
The dictionary has two required keys, ‘names’ and ‘formats’, and four optional keys, ‘offsets’, ‘itemsize’, ‘aligned’ and ‘titles’. The values for ‘names’ and ‘formats’ should respectively be a list of field names and a list of dtype specifications, of the same length.
Top answer
1 of 6
73

You could use np.array(list(result.items()), dtype=dtype):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = ['id','data']
formats = ['f8','f8']
dtype = dict(names = names, formats=formats)
array = np.array(list(result.items()), dtype=dtype)

print(repr(array))

yields

array([(0.0, 1.1181753789488595), (1.0, 0.5566080288678394),
       (2.0, 0.4718269778030734), (3.0, 0.48716683119447185), (4.0, 1.0),
       (5.0, 0.1395076201641266), (6.0, 0.20941558441558442)], 
      dtype=[('id', '<f8'), ('data', '<f8')])

If you don't want to create the intermediate list of tuples, list(result.items()), then you could instead use np.fromiter:

In Python2:

array = np.fromiter(result.iteritems(), dtype=dtype, count=len(result))

In Python3:

array = np.fromiter(result.items(), dtype=dtype, count=len(result))

Why using the list [key,val] does not work:

By the way, your attempt,

numpy.array([[key,val] for (key,val) in result.iteritems()],dtype)

was very close to working. If you change the list [key, val] to the tuple (key, val), then it would have worked. Of course,

numpy.array([(key,val) for (key,val) in result.iteritems()], dtype)

is the same thing as

numpy.array(result.items(), dtype)

in Python2, or

numpy.array(list(result.items()), dtype)

in Python3.


np.array treats lists differently than tuples: Robert Kern explains:

As a rule, tuples are considered "scalar" records and lists are recursed upon. This rule helps numpy.array() figure out which sequences are records and which are other sequences to be recursed upon; i.e. which sequences create another dimension and which are the atomic elements.

Since (0.0, 1.1181753789488595) is considered one of those atomic elements, it should be a tuple, not a list.

2 of 6
4

Similarly to the approved answer. If you want to create an array from dictionary keys:

np.array( tuple(dict.keys()) )

If you want to create an array from dictionary values:

np.array( tuple(dict.values()) )
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-a-dictionary-into-a-numpy-array
How to convert a dictionary into a NumPy array? - GeeksforGeeks
March 5, 2023 - First of all call dict.items() to return a group of the key-value pairs in the dictionary. Then use list(obj) with this group as an object to convert it to a list. At last, call numpy.array(data) with this list as data to convert it to an array.
🌐
New York University
physics.nyu.edu › pine › pymanual › html › chap3 › chap3_arrays.html
3. Strings, Lists, Arrays, and Dictionaries — PyMan 0.9.31 documentation
The NumPy library has a large set of routines for creating, manipulating, and transforming NumPy arrays. NumPy functions, like sqrt and sin, are designed specifically to work with NumPy arrays. Core Python has an array data structure, but it’s not nearly as versatile, efficient, or useful as the NumPy array.
🌐
NumPy
numpy.org › doc › stable › user › basics.rec.html
Structured arrays — NumPy v2.3 Manual
The dictionary has two required keys, ‘names’ and ‘formats’, and four optional keys, ‘offsets’, ‘itemsize’, ‘aligned’ and ‘titles’. The values for ‘names’ and ‘formats’ should respectively be a list of field names and a list of dtype specifications, of the same length.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to create a dictionary from two numpy arrays?
How to Create a Dictionary From Two NumPy Arrays? - Be on the Right Side of Change
January 22, 2021 - Unlike Python’s standard lists, which can hold different data types in a single list, NumPy’s arrays should be homogeneous, all the same data type. Otherwise we lose the mathematical efficiency built into a NumPy array. Having created two arrays, we can then use Python’s zip() function to merge them into a dictionary.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-convert-a-numpy-array-to-a-dictionary-in-python
How to convert a NumPy array to a dictionary in Python?
March 27, 2026 - import numpy as np # Creating a 3x3 NumPy array array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Convert numpy array to dictionary using enumerate and flatten dictionary = dict(enumerate(array.flatten(), 1)) print("Original array:") print(array) print(f"Array type: {type(array)}") print("\nResulting dictionary:") print(dictionary) print(f"Dictionary type: {type(dictionary)}")
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-numpy-array-to-dictionary-in-python
How to convert NumPy array to dictionary in Python? - GeeksforGeeks
July 23, 2025 - Space Complexity: The space complexity for converting a numpy array to a dictionary is O(n), where n is the number of elements in the numpy array.
🌐
NumPy
numpy.org › doc › stable › user › basics.rec.html
Structured arrays — NumPy v2.4 Manual
The dictionary has two required keys, ‘names’ and ‘formats’, and four optional keys, ‘offsets’, ‘itemsize’, ‘aligned’ and ‘titles’. The values for ‘names’ and ‘formats’ should respectively be a list of field names and a list of dtype specifications, of the same length.
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-a-dictionary-into-a-numpy-array
How to Convert a Dictionary into a NumPy Array?
July 21, 2023 - 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}")
🌐
pythontutorials
pythontutorials.net › blog › numpy-dictionary
Unleashing the Power of NumPy: A Deep Dive into NumPy Dictionaries — pythontutorials.net
Document the keys and the purpose of each value in the dictionary. This makes the code more understandable, especially for other developers or when revisiting the code after some time. NumPy dictionaries offer a flexible way to organize and manage NumPy arrays.
🌐
Reddit
reddit.com › r/learnpython › use numpy array of keys to pull values from dictionary?
r/learnpython on Reddit: Use numpy array of keys to pull values from dictionary?
March 23, 2022 -

I have about 200,000 records to iterate about and a list of group names whose corresponding values need to be pulled for each record.

import numpy as np

#Vectorized function to use array elements as keys to pull from dict
pull_dict = np.vectorize(lambda e,g: g[e])

#Group names to pull under each record
groups= []
groups.append(["A","B"])
groups.append(["A","C"])
groups.append(["C","D"])
groups = np.asarray(groups)

#Example of record_dicts for each record
# record_dict = {"A":1,"B":2,"C":3,"D":4} #Record 1
# record_dict = {"A":2,"B":3,"C":1,"D":4} #Record 2
# .
# .
# n (where n= 200000)

#For each record object
all_values = []
for record in records:
    
    #Pull dictionary stored inside record object
    record_dict = record["dict"]
    
    #Pull values
    values = pull_dict(groups,record_dict)
    all_values.append(values)

#Example Input/Output for Record #1 (0th index in loop)
#-----------------------------------------------------------

# #Input ndarray
# [["A","B"]
#  ["A","C"]
#  ["C","D"]]

# #Output ndarray (Ex: For record #1)
# [[1,2]
#  [1,3]
#  [3,4]]

There's about 200,000 records and the above code is just a sample. It takes about 8 seconds to go through this portion of code. Trying to optimize it to be as fast as possible. I am currently using a numpy vectorized function to treat each element as a key used to pull values from the dictionary. The vectorized function returns an ndarray of equal size to "groups". Each record has a unique dict that ties the group name to an integer.

Is there a more direct way to use an ndarray as a bunch of keys for pulling values from a dictionary? Looking for further speed reductions.

🌐
Edureka Community
edureka.co › home › community › categories › python › dictionary in numpy array
Dictionary in NumPy array | Edureka Community
How do I access the dictionary inside the array? import numpy as np x = np.array({'x': 2, 'y ... index x[0] Index Error: too many indices for array
🌐
Google Groups
groups.google.com › g › numpy › c › jPYRL3lp7Zg
[Numpy-discussion] Fastest way to save a dictionary of numpy record arrays
I tried numpy.save() but my dictionary is lost and >> cPickle seems to be slow. >> > > numpy.savez() will save a dictionary of arrays out to a .zip file. > Each key/value pair will map to a file in the .zip file with a file > name corresponding to the key.
🌐
Python Forum
python-forum.io › thread-13241.html
Dictionary or Numpy Array?
October 5, 2018 - First, can someone please show the proper code for creating a 5 row 2 column numpy array with type python object? I see a lot of info online but none of it seems to quite show how to do that in one example. Second, If I want to have a string for a k...
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-exercise-167.php
Python NumPy: Convert a Python dictionary to a Numpy ndarray - w3resource
August 29, 2025 - Write a NumPy program to convert a nested Python dictionary into a 2D array, ensuring the correct order of keys.
🌐
w3resource
w3resource.com › python-exercises › numpy › convert-a-numpy-array-to-a-dictionary-with-indices-as-keys.php
Convert a NumPy array to a dictionary with Indices as Keys
September 1, 2025 - Write a Numpy program to convert a 2D NumPy array into a dictionary where each key is a tuple representing row and column indices.
🌐
NumPy
numpy.org › devdocs › user › basics.rec.html
Structured arrays — NumPy v2.6.dev0 Manual
The dictionary has two required keys, ‘names’ and ‘formats’, and four optional keys, ‘offsets’, ‘itemsize’, ‘aligned’ and ‘titles’. The values for ‘names’ and ‘formats’ should respectively be a list of field names and a list of dtype specifications, of the same length.