0

I am converting a Python dictionary to NumPy array.

import numpy as np

myDict = {
        1: "AAA",
        2: "BBB",
        3: "CCC",
        4: "AAA",
        5: "BBB"
        }

myNumPyArray = np.asarray(myDict, dtype=dict, order="C")

print(myNumPyArray) 

Output

{1: 'AAA', 2: 'BBB', 3: 'CCC', 4: 'AAA', 5: 'BBB'}

Why is it showing the dictionary in the output?

6
  • You could do myNumPyArray = np.array(list(myDict.items())) instead. Commented Jul 18, 2019 at 8:30
  • Try printing the repr(myNumPyArray). Commented Jul 18, 2019 at 8:31
  • Possible duplicate of python dict to numpy structured array Commented Jul 18, 2019 at 8:31
  • 3
    the issue is, it's an array of a dict. Numpy cannot know how you want the dict to be inferred, also take a look at docs. Use .items.() or .values() on the dict before calling numpy array on it Commented Jul 18, 2019 at 8:32
  • 1
    What output do you expect? The manual says you should pass "lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays" for the first argument. Commented Jul 18, 2019 at 8:32

1 Answer 1

1

This "fails" because an array containing a single scalar value of type 'object' is created. This scalar value will be a pointer to the dictionary. If you want to transform content of the dictionary to ndarray you can use structured array with 2 fields. One for integer index, other for value as a fixed length string. Using np.fromiter is a fast method because it avoids creation of any temporary objects.

np.fromiter(myDict.items(), dtype='i4,U3', count=len(myDict))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.